2012-12-31 21 views
0

我有一個來自Echoonest API和Spotify URI的歌曲列表,但它增加了更多的歌曲,然後我需要。我只需要其中的一個不是全部,但我想繼續這樣做20次。所以我只想獲得節點內的第一個軌道,然後轉到下一個軌道。只選擇一個節點並在php上移動

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> 
+3

如果沒有查看XML或查看輸出結果,您不清楚您的意思。請更新您的問題。 –

+0

兩個具體點要澄清:a)「我只想獲得節點內的第一個軌道,並繼續到下一個節點(''?)和下一個什麼(播放列表?)的第一個軌道? b)你的代碼遍歷''元素,但你的例子只包含一個元素,而它下面沒有''節點;這個代碼實際上工作嗎? – IMSoP

回答

0

所以我只想要得到的節點內的第一首曲目,並移動到下一個。

您正在描述continue - 將移至下一次迭代並跳過當前循環中的以下代碼。 break結束當前循環。

+0

但數量的機會取決於它得到多少結果,所以我永遠不知道應該跳過多少結果。那我該怎麼做呢? –

0

可通過計算結果獲取的歌曲數量:

$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

希望這是有幫助的。正如已經評論的那樣,你的問題並不清楚。我希望計數和編號訪問將允許您至少以編程方式選擇要查找的元素。

相關問題