views:

242

answers:

2

Hi folks, I'm new to this so bear with my noobish question.

Basically I want a user to enter a search phrase into a web-form and for the query to be passed to the lastFM API and return top artists using that phrase based on their "gettopartists" API node. Here's the code I have...

function last($q){ $target_url='http://ws.audioscrobbler.com/2.0/?format=json&method=tag.gettopartists&api_key=....&tag=' . $q . ''; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$target_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); $return = curl_exec($ch);

}

Obviously within that I get a valid return by printing "echo $return;" but I've no idea how to parse it correctly. No matter how many foreach arguments I put in I cannot avoid an error or no output at all...

Thanks folks...

A: 

You should take a look at the PHP documentation for json_decode. It builds a stdClass object (or associative arrays) from JSON which you can them loop over to your hearts content.

Steve
+1  A: 

I assume you are talking about this function: http://www.last.fm/api/show?service=300

If you leave out the format=json part, it will get returned as xml

The sample response looks like it's in XML format, in that case you can parse it with PHP's SimpleXML http://php.net/manual/en/ref.simplexml.php

http://www.ibm.com/developerworks/library/x-simplexml.html

You also have format=json, which leads me to believe that it might be returned in JSON format, in which case you would use json_decode.

$json = '{"foo-bar": 12345}';

$obj = json_decode($json); echo $obj->{'foo-bar'}; // 12345

Stanislav Palatnik
Cheers. Will look into that further.
Kevin