问题
I have a JSON structure such as http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&api_key=XXXX&format=json and I'd like to pick out various bits of information such as similar artists (names and images), tags, the extralarge image, content etc
I got the similar arists working by using
<?php
$url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Queens%20Of%20the%20STone%20Age&api_key=XXX&format=json';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['artist']['similar']['artist'] as $item) {
print $item['name'];
print '<br>';
}
?>
However, how do I extract the "large" image from the following:
"artist": [{
"name": "Them Crooked Vultures",
"url": "http:\/\/www.last.fm\/music\/Them+Crooked+Vultures",
"image": [{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/34\/38985285.jpg",
"size": "small"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/64\/38985285.jpg",
"size": "medium"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/126\/38985285.jpg",
"size": "large"
}]
Thanks,
JJ
ALL SORTED! Finished product: http://www.strictlyrandl.com/artist/queens-of-the-stone-age/
回答1:
You'll need to loop through the images and print it:
foreach($json['artist']['similar']['artist'] as $item) {
print $item['name'];
print '<br>';
for ($i=0; $i < count($item['image']); $i++) {
echo $item['image'][$i]['#text']."<br>";
}
}
To print them only if they're of size large or extra large, you can use a simple if
statement:
for ($i=0; $i < count($item['image']); $i++) {
echo $item['image'][$i]['#text']."<br>";
if($item['image'][$i]['size'] == 'extralarge') {
echo $item['image'][$i]['#text']."<br>";
}
}
回答2:
$get = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&api_key=63692beaaf8ba794a541bca291234cd3&format=json');
$get = json_decode($get);
echo '<pre>';
//print_r($get->artist);
echo '</pre>';
echo '<strong>Artist Name = </strong>'.$get->artist->name.'<br/>
<strong>Artist mbid = </strong>'.$get->artist->mbid.'<br/>
<strong>Artist Url = </strong>'.$get->artist->url.'<br/>
<strong>Artist İmage = </strong><br/>';
foreach($get->artist->image as $image) {
$image = (array) $image;
echo 'İmage Text = '.$image['#text'].'<br />
İmage Size = '.$image['size'].'<br />';
}
来源:https://stackoverflow.com/questions/18713627/php-and-last-fm-api