user1157393
user1157393

Reputation:

XML instead of json

I am trying to connect to an API with an XML response. I have it working in json (see below) but i need it to return in xml instead.

//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");

$url = 'http://api.klout.com/1/klout.xml?users=username&key=keyhere';

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);

$arr = json_decode($r,true);

foreach($arr['users'] as $val)
{
        echo $val['kscore'].'<br>';
        echo $val['twitter_screen_name'].'<br>';
}

Thanks.

Chris

Upvotes: 1

Views: 1452

Answers (1)

lorenzo-s
lorenzo-s

Reputation: 17010

The API you are using returns data in XML format. So, you cannot use json_decode() to parse it, obviously. Instead, you should look to SimpleXML. It's the default PHP library to parse and write XML data, and usually it comes installed by default with PHP.

You can start with this nice tutorial:

http://www.phpro.org/tutorials/Introduction-To-SimpleXML-With-PHP.html

Or if you want to start very very quickly:

http://www.w3schools.com/php/php_xml_simplexml.asp

It's very easy to use it to parse XML data.

Upvotes: 1

Related Questions