Nirali Joshi Nirali Joshi - 7 days ago 4
PHP Question

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?

Answer

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