使用php读取xml响应

时间:2016-12-01 07:16:15

标签: php xml

我有一个XML格式的Api响应。我怎样才能获得两个元素的gps_x和gps_y。

$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";

$xmlinfo = simplexml_load_file($url);

print_r($xmlinfo);

echo $xmlinfo['gps_x']; // outputs nothing
echo $xmlinfo -> gps_x; // outputs nothing

如何从上面的回复中获取gps_x和gps_y?

3 个答案:

答案 0 :(得分:3)

我是通过从url获取内容然后使用异常处理转换为json并从解码的json获取数据来实现的:

<?php   

$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$jsondata = json_encode($simpleXml) or die("Error: Cannot encode record to json");
$data = json_decode($jsondata, true);
$in = $data['items']['item'];
foreach ($in as $key => $value) {
    echo "ID= " . $in[$key]['id'] . ", GPS-x = " . $in[$key]['gps_x'] . ", GPS-y = " . $in[$key]['gps_x'];
    echo "<br/>";
}   

?>

输出

  

ID = 2354292,GPS-x = 36.1065000000,GPS-y = 36.1065000000

     

ID = 2431066,GPS-x = 36.0949905151,GPS-y = 36.0949905151

如果您想直接从XML获取数据:

<?php   

$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$in = $simpleXml->items->item;
foreach ($in as $key) {
    echo "ID= " . $key->id;
    echo ", GPS-x = " . $key->gps_x;
    echo ", GPS-y = " . $key->gps_y . "<br/>";
}

?>

<强>输出

  

ID = 2354292,GPS-x = 36.1065000000,GPS-y = 28.0684000000

     

ID = 2431066,GPS-x = 36.0949905151,GPS-y = 28.0860328674

答案 1 :(得分:2)

查看print_r()输出,显示gps_x&amp; gps_y是项目的一部分,而不是直接位于xmlinfo对象下。 以下是完成这项工作的代码:

$url = "http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";

$xmlinfo = simplexml_load_file($url);
if ($xmlinfo->items && $xmlinfo->items->item) {
    $item = $xmlinfo->items->item;
    print $item->gps_x . "\n";
    print $item->gps_y . "\n";
}

答案 2 :(得分:1)

$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";

$xmlinfo = simplexml_load_file($url);

foreach ($xmlinfo->items->item as $item) {
    //echo "<pre>";print_r($item);
    echo "<br />". $item->gps_x;
    echo "<br />". $item->gps_y;    
}