2016-12-01 108 views
2

我有一個XML格式的Api響應。如何爲這兩個元素獲取gps_x和gps_y。使用php讀取xml響應

$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

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

?> 

OUTPUT

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

?> 

OUTPUT

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

ID = 2431066,GPS-X = 36.0949905151,GPS-Y = 28.0860328674

2

綜觀print_r()輸出,它表明gps_x & 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"; 
} 
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;  
}