循环遍历此XML文件,直到找到PHP的特定艺术家名称

时间:2016-01-24 02:08:42

标签: php xml loops filter

我需要帮助。我有一个大型XML文件,其中包含我需要扫描的艺术家信息。我需要做的是遍历此文件,直到找到艺术家名称。然后只抓住那个特定艺术家的子元素。

例如,以下是列出几位艺术家的xml文件的一部分:

<artists page="1" perPage="100" totalPages="253081" total="25308020">
<artist>
<name>David Bowie</name>
<playcount>151727648</playcount>
<listeners>3969219</listeners>
<mbid>5441c29d-3602-4898-b1a1-b77fa23b8e50</mbid>
<url>http://www.last.fm/music/David+Bowie</url>
<streamable>0</streamable>
<image size="small">
http://img2-ak.lst.fm/i/u/34s/937d62bb145040b9b709319c1e680037.png
</image>
<image size="medium">
http://img2-ak.lst.fm/i/u/64s/937d62bb145040b9b709319c1e680037.png
</image>
<image size="large">
http://img2-ak.lst.fm/i/u/174s/937d62bb145040b9b709319c1e680037.png
</image>
<image size="extralarge">
http://img2-ak.lst.fm/i/u/300x300/937d62bb145040b9b709319c1e680037.png
</image>
<image size="mega">
http://img2-ak.lst.fm/i/u/937d62bb145040b9b709319c1e680037.png
</image>
</artist>
<artist>
<name>The Beatles</name>
<playcount>456495139</playcount>
<listeners>3986977</listeners>
<mbid>b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d</mbid>
<url>http://www.last.fm/music/The+Beatles</url>
<streamable>0</streamable>
<image size="small">
http://img2-ak.lst.fm/i/u/34s/55efc33bcd234fd8a1d65b3d49bf9661.png
</image>
<image size="medium">
http://img2-ak.lst.fm/i/u/64s/55efc33bcd234fd8a1d65b3d49bf9661.png
</image>
<image size="large">
http://img2-ak.lst.fm/i/u/174s/55efc33bcd234fd8a1d65b3d49bf9661.png
</image>
<image size="extralarge">
http://img2-ak.lst.fm/i/u/300x300/55efc33bcd234fd8a1d65b3d49bf9661.png
</image>
<image size="mega">
http://img2-ak.lst.fm/i/u/55efc33bcd234fd8a1d65b3d49bf9661.png
</image>
</artist>
</artists>

让我们说我正在搜索这个大文件,以获取特定于&#34;甲壳虫乐队&#34;的信息。我怎么会循环浏览这个文件,直到它到达披头士乐队&#39;部分,然后只获取特定于他们的信息(特别是图像大小 - ?)

当然,我可以简单地遍历整个文件并以这种方式抓取元素,但是对于所有艺术家来说:

$xml = simplexml_load_file($hot_artists_file);
$artist = $xml->artists->artist;

for ($i = 0; $i < 10; $i++) {
        $artist_name = $artist->name;
        $artist_url = $artist->url;
        $artist_pic_large = $artist->image[2];
        $artist_pic_mega = $artist->image[4];
        $artist_id = $artist->mbid;
        $artist_play_count = $artist->playcount;
        $artist_listeners = $artist->listeners;
    }

我试图使用xpath,但我一直收到Invalid Expression错误。然后我尝试了一个while()循环,它也没有工作。有人能指出我正确的方向吗?

如果您需要更多信息,我很乐意提供。一如既往,谢谢。

1 个答案:

答案 0 :(得分:1)

在XPath中,您可以使用谓词([])来过滤具有特定条件的元素,例如:

.....
$artist = $xml->xpath("/artists/artist[name='The Beatles']")[0]; 
echo $artist->name;

<强> eval.in demo

输出

The Beatles

上述XPath表示查找artist元素,它是artists的直接子元素,并且子元素name值等于"The Beatles"