1

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

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • See this post - http://stackoverflow.com/a/856887/201648. Not quite what you're doing, but should solve your problem. Short answer, PEAR XML Serializer should help http://pear.php.net/package/XML_Serializer. If you can post a sample of the curled data I can take a crack at it for you, although I'm going to bed in a minute. – Aaron Newton Feb 20 '12 at 12:34
  • 1
    Can you please clarify what you mean by "I have it working in json". Have you successfully decoded a JSON response from that service and want to decode an alternate XML response from the same service? After reading other responses I've realised this statement is ambiguous. – Aaron Newton Feb 20 '12 at 12:53

1 Answers1

1

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.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
  • Thanks for your help. Here is what i have now and I cannot get it to work no matter what. `users->user->kscore as $a){ echo $a; } ?>` Thanks, Chris –  Feb 20 '12 at 13:44
  • @ChrisTill I can't help you because I cannot get XML (I have a *Not Authorized* response). PHP gives you errors or what? I would be glad to help you, so if you can paste both PHP code and XML response content somewhere (i.e. *[PasteBin](http://pastebin.com/)*)... – lorenzo-s Feb 20 '12 at 14:48