简体   繁体   中英

Read xml response using php

I have a Api response in XML format.How can I get gps_x and gps_y for both elements.

$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

How can I get gps_x and gps_y from above response?

I did this by getting the content from url then converting to json using exceptions handling and get the data from decoded 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/>";
}   

?>

OUTPUT

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

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

If you want to take the data from XML directly:

<?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/>";
}

?>

OUTPUT

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

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

Looking at the print_r() output, it show that the gps_x & gps_y are part of an item and not directly under the xmlinfo object. Here is the code that will do the job:

$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";
}
$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;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM