【发布时间】:2020-02-11 15:31:34
【问题描述】:
希望你能帮我解决我的问题...
我有这个 XML 文件,我正在使用函数 simplexml_load_file() 获取信息:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<Xiami>
<ArtistID>179</ArtistID>
<ArtistName>Band 1</ArtistName>
<XiamiID>9dl4gN1c745</XiamiID>
<Streaming>246</Streaming>
<Fans>84</Fans>
<TotalComments>1992</TotalComments>
<AllSongs>
<Songs>
<SongID>8ILroS998dc</SongID>
<SongName>Song 1</SongName>
<SongComments>9223</SongComments>
</Songs>
<Songs>
<SongID>8ILLD61a351</SongID>
<SongName>Song 2</SongName>
<SongComments>7221</SongComments>
</Songs>
<Songs>
<SongID>mTnf0L5d6b9</SongID>
<SongName>Song 3</SongName>
<SongComments>21212</SongComments>
</Songs>
<Songs>
<SongID>xOd2YIc7f69</SongID>
<SongName>Song 4</SongName>
<SongComments>422</SongComments>
</Songs>
<Songs>
<SongID>mTmg866314c</SongID>
<SongName>Song 5</SongName>
<SongComments>81211</SongComments>
</Songs>
</AllSongs>
</Xiami>
</rss>
这是我用来获取数据的代码:
<?php
foreach($xml->children() as $Artist) {
$ArtistName = $Artist->ArtistName;
$Streaming = $Artist->Streaming;
$Fans = $Artist->Fans;
$SongsArrays = $Artist->AllSongs;
$SongsCount = $Artist->AllSongs->Song->count();
}
?>
如果我打印 print_r($SongsArrays),我会得到以下数组:
SimpleXMLElement Object
(
[Song] => Array
(
[0] => SimpleXMLElement Object
(
[SongID] => 8ILroS998dc
[SongName] => Song 1
[SongComments] => 9223
)
[1] => SimpleXMLElement Object
(
[SongID] => 8ILLD61a351
[SongName] => Song 2
[SongComments] => 7221
)
[2] => SimpleXMLElement Object
(
[SongID] => mTnf0L5d6b9
[SongName] => Song 3
[SongComments] => 21212
)
[3] => SimpleXMLElement Object
(
[SongID] => xOd2YIc7f69
[SongName] => Song 4
[SongComments] => 422
)
[4] => SimpleXMLElement Object
(
[SongID] => mTmg866314c
[SongName] => Song 5
[SongComments] => 81211
)
)
)
如果我打印整个数组,我会得到这个:
SimpleXMLElement Object
(
[ArtistID] => 179
[ArtistName] => Band 1
[XiamiID] => 9dl4gN1c745
[Streaming] => 246
[Fans] => 84
[AllSongs] => SimpleXMLElement Object
(
[Song] => Array
(
[0] => SimpleXMLElement Object
(
[SongID] => 8ILroS998dc
[SongName] => Song 1
[SongComments] => 9223
)
[1] => SimpleXMLElement Object
(
[SongID] => 8ILLD61a351
[SongName] => Song 2
[SongComments] => 7221
)
[2] => SimpleXMLElement Object
(
[SongID] => mTnf0L5d6b9
[SongName] => Song 3
[SongComments] => 21212
)
[3] => SimpleXMLElement Object
(
[SongID] => xOd2YIc7f69
[SongName] => Song 4
[SongComments] => 422
)
[4] => SimpleXMLElement Object
(
[SongID] => mTmg866314c
[SongName] => Song 5
[SongComments] => 81211
)
)
)
)
问题是:
- 如何提取具有更多 cmets 的前 3 首歌曲(获取 cmets、名称和 ID)
- 如何将所有 cmets 相加?...
我已经尝试了谷歌和其他论坛推荐的几乎所有东西,但是如果不编写大量代码(分离每个数组并创建大量循环)就找不到如何获取这些数据......有没有更快更简单的方法这样做?
【问题讨论】: