XML instead of json


XML instead of json

我正在尝试连接到带有XML响应的API。我让它在json中工作(见下文),但我需要它以xml形式返回。

//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>';
}

谢谢。

Chris

您使用的API以XML格式返回数据。因此,显然不能使用json_decode()来解析它。相反,您应该关注SimpleXML。它是解析和编写XML数据的默认PHP库,通常默认情况下与PHP一起安装。

你可以从这个不错的教程开始:

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

或者,如果你想很快开始:

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

使用它来解析XML数据非常容易。