2

好吧,所以我对此有点困惑。我有一个看起来像这样的 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" } 
} 

现在我如何只获得艺术家,而不是整个 SimpleXMLElement,因为我无法弄清楚。

4

4 回答 4

5

The items you are adding to the array are SimpleXMLElements. If you just want to add the string value, you must cast the SimpleXMLElement to a string.

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

var_export($artists);

In general, you always want to cast SimpleXMLElement to a string when you want the string value. In some cases PHP will automatically coerce to string (for example when you echo it), but PHP type coercion rules are so complicated that it's better to always be explicit.

(Also, there is no need for array_push(), just use the bracket notation $arrayname[] = $appendedvalue.)

于 2012-10-31T14:23:17.150 回答
1

var_dump是为您提供可用于访问不同部分的密钥,并且转换为字符串将为您提供节点值,请尝试:

$artist = (string) $track->artist[0];
于 2012-10-31T14:11:17.107 回答
0

看看这些链接......他们过去曾帮助过我。

http://www.bookofzeus.com/articles/convert-simplexml-object-into-php-array/

http://milesj.me/blog/read/simplexml-to-array

于 2012-10-31T14:14:23.630 回答
0

试试下面的代码。

$xml = simplexml_load_file("artist.xml");

echo $xml->artist;
于 2012-10-31T14:16:50.820 回答