所以我试图遍历一个看起来像这样的DOM文档:
<track rank="1">
<name>Believe</name>
<duration>239</duration>
<mbid>13194c93-89c6-4ab4-aaf2-15db5d73b74e</mbid>
<url>http://www.last.fm/music/Cher/_/Believe</url>
<streamable fulltrack="0">0</streamable>
<artist>
<name>Cher</name>
<mbid>bfcc6d75-a6a5-4bc6-8282-47aec8531818</mbid>
<url>http://www.last.fm/music/Cher</url>
</artist>
</track>
使用PHP我可以做$tracks = $xml->getElementsByTagName("track");
事实是,对于每个轨道,我想要检索其名称和持续时间。我知道childNodes属性,但我不会将它们全部循环。有没有办法直接访问它们而不使用foreach对其子女?
答案 0 :(得分:0)
<?php
$doc = new DOMDocument;
$doc->load('example.xml');
$xpath = new DOMXPath($doc);
$tracks = array();
foreach ($xpath->query('//track') as $track) {
$tracks[] = array(
'name' => $xpath->evaluate('string(name)', $track),
'duration' => $xpath->evaluate('number(duration)', $track),
);
}
print_r($tracks);