将xml对象推入数组

use*_*846 2 php xml arrays

哦,所以我对此有点困惑.我有一个看起来像这样的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>
Run Code Online (Sandbox Code Playgroud)

我使用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);
Run Code Online (Sandbox Code Playgroud)

现在我希望得到一个看起来像这样的好阵列:

array(4) {
[0]=>
string(20) "Red Hot Chili Peppers "
[1]=>
string(20) "Red Hot Chili Peppers"
}
Run Code Online (Sandbox Code Playgroud)

但我得到的是这样的:

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" } 
} 
Run Code Online (Sandbox Code Playgroud)

现在我如何才能获得艺术家,而不是整个SimpleXMLElement,因为我无法理解它.

Fra*_*ila 5

您要添加到阵列的项目是SimpleXMLElements.如果您只想添加字符串值,则必须将其SimpleXMLElement转换为字符串.

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

var_export($artists);
Run Code Online (Sandbox Code Playgroud)

通常,您希望SimpleXMLElement在需要字符串值时强制转换为字符串.在某些情况下,PHP会自动强制转换为字符串(例如,当你使用echo它时),但PHP类型强制规则是如此复杂以至于最好总是显式的.

(另外,没有必要array_push(),只需使用括号表示法$arrayname[] = $appendedvalue.)