Php 从这一行获得<;topalbums艺人=“唱片公司”;“阿黛勒”&燃气轮机;

Php 从这一行获得<;topalbums艺人=“唱片公司”;“阿黛勒”&燃气轮机;,php,api,last.fm,Php,Api,Last.fm,大家好,我正在尝试从last.fm获取信息,我正在获取专辑名称等,但我想从第2行获取信息。如何得到它 <topalbums artist="Adele" page="1" perPage="1" totalPages="55092" total="55092"> ^从此处开始名称、页码、每页和总页数 <lfm status="ok"> <topalbums artist="Adele" page="1" perPage="1" totalPages="5509

大家好,我正在尝试从last.fm获取信息,我正在获取专辑名称等,但我想从第2行获取信息。如何得到它

<topalbums artist="Adele" page="1" perPage="1" totalPages="55092" total="55092">

^从此处开始名称、页码、每页和总页数

<lfm status="ok">
<topalbums artist="Adele" page="1" perPage="1" totalPages="55092" total="55092">
<album>

<name>21</name>
<playcount>52308837</playcount>
<mbid>c45e0e0e-48c9-4441-aac3-2f2b34202d3c</mbid>
<url>https://www.last.fm/music/Adele/21</url>
<artist>

<name>Adele</name>
<mbid>cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493</mbid>
<url>https://www.last.fm/music/Adele</url>
</artist>
<image size="small">
https://lastfm-img2.akamaized.net/i/u/34s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="medium">
https://lastfm-img2.akamaized.net/i/u/64s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="large">
https://lastfm-img2.akamaized.net/i/u/174s/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
<image size="extralarge">
https://lastfm-img2.akamaized.net/i/u/300x300/c894af1e6a735b9bbb2a0312c7719f40.png
</image>
</album>
</topalbums>
</lfm>

21
52308837
c45e0e0e-48c9-4441-aac3-2F2B34202C
https://www.last.fm/music/Adele/21
阿黛尔
cc2c9c3c-b7bc-4b8b-84d8-4BD8779E493
https://www.last.fm/music/Adele
https://lastfm-img2.akamaized.net/i/u/34s/c894af1e6a735b9bbb2a0312c7719f40.png
https://lastfm-img2.akamaized.net/i/u/64s/c894af1e6a735b9bbb2a0312c7719f40.png
https://lastfm-img2.akamaized.net/i/u/174s/c894af1e6a735b9bbb2a0312c7719f40.png
https://lastfm-img2.akamaized.net/i/u/300x300/c894af1e6a735b9bbb2a0312c7719f40.png

一种基本方法是使用正则表达式:

preg_match('/artist="([^"]*)"\\s*page="([^"]*)"\\s*perPage="([^"]*)"\\s*totalPages="([^"]*)"/', $lastfm_input, $result);
# $result[1] = name value
# $result[2] = page value
# $result[3] = perPage value
# $result[4] = totalPages value

如果属性的顺序(如
perPage
)发生变化,则必须使用多个正则表达式。

有趣的是,我找到了最佳解决方案

$dom = new DOMDocument();
$dom->loadXML($xml);
$topAlbums = $dom->getElementsByTagName('topalbums')->item(0);
$artist = $topAlbums->getAttribute('artist');
echo $artist; // outputs Adele
<?php 
$attrs = $xml7->topalbums->attributes();
echo $attrs["total"];
?>
topalms->attributes();
echo$attrs[“总计”];
?>

复制/粘贴或使用DOMDocument或SimpleXML的快捷方式。。。你试过什么?例如,我试过($xml作为$albums)$adele=albums->topalbums->adeleNo,完全错了。Regex不应该解析HTML或XML,有一篇著名的堆栈溢出帖子,请查阅。我同意最好使用解析器,我只想介绍一下这个选项。(因为做这件事的方法总是不止一种,它可能会帮助其他人解决另一个类似的问题。)你有你提到的帖子的链接吗?当然,享受吧!:-D非常好!:D我认为对这个问题的投票率第二高的答案解释了为什么我对一些用于随意从XML字符串中提取数据的正则表达式没有问题。:)