问题
I have a list of songs from Echonest API with Spotify URI but it adds many more songs then I need. I only need one of them not all of them but I want to keep on doing this 20 times. So I only want to get the first track inside the node and move on to the next.
Here is the xml file I get the info from
This is the PHP I use:
<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>
回答1:
So I only want to get the first track inside the node and move on to the next.
You are describing continue - which moves to the next iteration and skips the following code in the current loop. Whereas break
ends the current loop.
回答2:
You can retrieve the number of songs by counting the result:
$numberOfSongsElements = count($xml->xpath('//songs'));
This should allow to find out if the song you want to retrieve is in there. For example:
$playlistNumber = 1;
if ($playlistNumber > $numberOfSongsElements) {
throw new Exception('Not enough <songs> elements');
}
$songsElement = $xml->xpath("//songs[$playlistNumber]");
By using the position number inside the Xpath predicate:
//songs[1] -- abbreviated form of: //songs[position()=1]
//songs[2]
//songs[3]
...
You can directly select the node you're interested in, be it first (1
) or some other number or even last (last()
). See 2.4 Predicates and 4.1 Node Set Functions.
Hope this is helpful. As already commented, your question was not that clear. I hope the counting and numbered access will allow you to select the element you're looking for at least programmatically.
来源:https://stackoverflow.com/questions/14103468/select-only-one-node-and-move-on-php