我有以下代码
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
$artistTag= $xml->artist->children();
$largeImage = $artistTag[7];
echo '<img src="'.$largeImage.'" />';
?>
这将针对第7个节点 - 但是第7个节点可能不存在,因此这将不起作用。无论如何专门针对大型,超大型或巨型节点?
示例XML
<lfm status="ok">
<artist>
<name>Metallica</name>
<mbid>65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab</mbid>
<url>http://www.last.fm/music/Metallica</url>
<image size="small">
http://img2-ak.lst.fm/i/u/34s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="medium">
http://img2-ak.lst.fm/i/u/64s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="large">
http://img2-ak.lst.fm/i/u/174s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="extralarge">
http://img2-ak.lst.fm/i/u/300x300/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="mega">
http://img2-ak.lst.fm/i/u/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="">
http://img2-ak.lst.fm/i/u/arQ/c14fdad46a5c423f86a683501c163c99.png
</image>
所以如果mega不存在,那就去扩大,如果不存在,那就去大看等
答案 0 :(得分:0)
这可能与以下内容重复:SimpleXML: Selecting Elements Which Have A Certain Attribute Value
以下是我对您的具体案例的看法:
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
$largeImage = $xml->xpath('/lfm/artist/image[@size="mega"]')[0];
echo '<img src="'.$largeImage.'" />';
?>
答案 1 :(得分:0)
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
$largeImage = $xml->xpath('/lfm/artist/image[@size="mega"]')[0];
echo '<img src="'.$largeImage.'" />';
?>