好吧,所以我有点困惑。我有一个类似这样的XML:

<track>
<artist mbid="77cceea7-91bb-4a4c-ae41-bc9c46c1ccb5"> Red Hot Chili Peppers </artist>
<name> under the bridge </name>
<streamable>0</streamable>
<mbid/>
<album mbid="0fe94139-df63-4e51-b2e7-a1d53535cdd9">  Blood Sugar Sex Magik </album>
<url> http://xxxxxx.com </url>
<date uts="1351691244">31 Oct 2012, 13:47</date>
</track>

我使用simplexml来解析xml,如下所示:
$artists = array();

$xml = simplexml_load_file("http://xxxxxxxxxxxxxx");

foreach($xml->recenttracks->track  as $track)
{
$artist = $track->artist;
    array_push($artists, $artist);
}

var_dump($artists);

现在我希望得到一个这样的阵列:
array(4) {
[0]=>
string(20) "Red Hot Chili Peppers "
[1]=>
string(20) "Red Hot Chili Peppers"
}

但我得到的是这样的东西:
array(2)
{
[0]=> object(SimpleXMLElement)#6 (2) { ["@attributes"]=> array(1) { ["mbid"]=> string(36) "8bfac288-ccc5-448d-9573-c33ea2aa5c30" } [0]=> string(21) "Red Hot Chili Peppers" }
[1]=> object(SimpleXMLElement)#4 (2) { ["@attributes"]=> array(1) { ["mbid"]=> string(36) "8bfac288-ccc5-448d-9573-c33ea2aa5c30" } [0]=> string(21) "Red Hot Chili Peppers" }
}

现在我怎样才能只得到艺术家,而不是整个简单的元素,因为我就是想不出来。

最佳答案

要添加到数组中的项是SimpleXMLElements。如果只想添加字符串值,则必须将SimpleXMLElement强制转换为字符串。

$artists = array();
foreach($xml->recenttracks->track  as $track)
{
    $artists[] = (string) $track->artist;
}

var_export($artists);

通常,当需要字符串值时,总是希望将SimpleXMLElement强制转换为字符串。在某些情况下,php会自动强制为string(例如当echoit时),但是php类型强制规则非常复杂,最好总是显式的。
(同样,不需要array_push(),只需使用括号符号$arrayname[] = $appendedvalue

10-05 22:11