Get info from JSON file and turn it into a PHP String

86 views Asked by At

I want to connect with the last fm API and pulling the information from the JSON file.

Example file : [Last FM API JSON File][1]

on my php file I get the correct information via this code :

<?$get = file_get_contents('http://ws.audioscrobbler.com/2.0/?
method=artist.getinfo&artist=Ed 
Sheeran&api_key=63692beaaf8ba794a541bca291234cd3&format=json');
$get = json_decode($get);
foreach($get->artist->tags->tag as $tags) { $thetag = (array) $thetag;?>
<? echo $thetag['name'];?> 
<?} ?> 

At the moment this will echo each individual tag for that artist, for example : easy listening and grime

What i am wondering is there any way to create a string that contains $thetag whilst also putting a comma inbetween?

$newstring = "easy listening, grime"  

e.t.c

My plan is to create the string and then use php code to search my database and display records where the tag column contains any of those tags. Any idea how is it possible?

[1]: http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Ed Sheeran&api_key=63692beaaf8ba794a541bca291234cd3&format=json

2

There are 2 answers

0
TimBrownlaw On BEST ANSWER

This is tested and working and is one of a few possible methods...

<?php
$song_list_json = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Ed Sheeran&api_key=63692beaaf8ba794a541bca291234cd3&format=json');
$song_list = json_decode($song_list_json);

$name_tags = array();
foreach ($song_list->artist->tags->tag as $tags) {
    $name_tags[] = $tags->name;
}
$song_names = implode(', ',$name_tags);

// Do something with it...
echo $song_names;
2
camelsWriteInCamelCase On

You can parse the JSON string as array. Then use array_map function to iterate through $array['artist']['tags']['tag'] array to get only name values.

// $json contains JSON string from API response to ws.audioscrobbler.com.
$array = json_decode($json, true);
$tags = '';

if (!empty($array['artist']['tags']['tag'])) {
    $tags = array_map(
        function($tag) {
            return isset($tag['name']) ? $tag['name'] : '';
        }, $array['artist']['tags']['tag']);
    $tags = implode(', ', $tags);
}