【问题标题】:select only one node and move on php只选择一个节点并继续 php
【发布时间】:2012-12-15 17:21:35
【问题描述】:

我有一个来自 Echonest API 的带有 Spotify URI 的歌曲列表,但它添加了我需要的更多歌曲。我只需要其中一个而不是全部,但我想继续这样做 20 次。所以我只想获取节点内的第一个轨道并继续下一个。

Here is the xml file I get the info from

这是我使用的 PHP:

<iframe src="https://embed.spotify.com/?uri=spotify:trackset:Playlist based on Rihanna:<?php 
$completeurl = "http://developer.echonest.com/api/v4/playlist/static?api_key=FILDTEOIK2HBORODV&artist=Rihanna&format=xml&results=20&type=artist-radio&bucket=tracks&bucket=id:spotify-WW"; 
$xml = simplexml_load_file($completeurl); 
$i = 1;
foreach ($xml->xpath('//songs') as $playlist) {
    $spotify_playlist = $playlist->foreign_id;
    $spotify_playlist2 = str_replace("spotify-WW:track:",'',$spotify_playlist);
    echo  "$spotify_playlist2,"; 
    if ($i++ == 10) break;
}
?>" width="300" height="380" frameborder="0" allowtransparency="true" style="float: right"></iframe>

【问题讨论】:

  • 如果不查看 XML 或查看输出,您将不清楚您的确切含义。请更新您的问题。
  • 需要澄清两个具体点:a)“我只想获取节点内的第一个轨道并移动到下一个”节点内的第一个轨道(&lt;song&gt;?)和下一个什么(播放列表?)? b) 您的代码在 &lt;songs&gt; 元素上循环,但您的示例仅包含一个,并且它下面没有 &lt;foreign_id&gt; 节点;这段代码真的有效吗?

标签: php xml foreach simplexml


【解决方案1】:

所以我只想获取节点内的第一条轨道,然后继续下一条。

您正在描述continue - 它移动到下一次迭代并跳过当前循环中的以下代码。而break 结束当前循环。

【讨论】:

  • 但是概率取决于它得到多少结果,所以我永远不知道它应该跳过多少.. 那我该怎么做呢?
【解决方案2】:

您可以通过计算结果来检索歌曲的数量:

$numberOfSongsElements = count($xml->xpath('//songs'));

这应该可以确定您要检索的歌曲是否在其中。例如:

$playlistNumber = 1;
if ($playlistNumber > $numberOfSongsElements) {
    throw new Exception('Not enough <songs> elements');
}
$songsElement = $xml->xpath("//songs[$playlistNumber]");

通过使用 Xpath 谓词内的位置编号:

//songs[1]  --  abbreviated form of: //songs[position()=1]
//songs[2]
//songs[3]
...

您可以直接选择您感兴趣的节点,可以是第一个 (1) 或其他数字,甚至是最后一个 (last())。请参阅2.4 Predicates4.1 Node Set Functions

希望这会有所帮助。正如已经评论的那样,您的问题并不那么清楚。我希望计数和编号访问将允许您至少以编程方式选择要查找的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多