2014-06-16 77 views
0

我想從雅虎請求YQL結果返回所有「名」的值返回地名,但我得到的是一個空白頁:(這是我到目前爲止的代碼:如何從雅虎YQL結果XML

$input = $_GET['str']; 
$yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%20='".$input."'"; 

$feed = file_get_contents($yql); 
$xml = simplexml_load_string($feed); 

echo $xml->query->results->place->name; 

我如何解析和名稱爲「名」返回所有的XML值

返回的XML結構示例:sample

非常感謝您的幫助:)

回答

1

由於您已經獲得了在yahoo yql上查詢所需的值,因此獲取值,因爲這是一個查詢,它產生了許多結果。你需要循環它,因爲它返回了多個結果。

看看這個例子:(紐約爲例)

$input = 'york'; 
$yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%20='".$input."'"; 
$contents = file_get_contents($yql); 
$xml = new SimpleXMLElement($contents); 
$places = array(); 
foreach($xml->results->place as $key => $item) { 
    $country_info = $item->country->attributes(); 
    $places[] = array(
     'placeTypeName' => (string) $item->placeTypeName, 
     'name' => (string) $item->name, 
     'country' => array(
      'code' => (string) $country_info['code'], 
      'type' =>(string) $country_info['type'], 
      'woeid' => (string) $country_info['woeid'], 
     ), 
    ); 
} 

print_r($places); 

所有的name值都在裏面$places

Sample Output

+0

非常感謝您的回答! :)我的最後一個問題:我怎樣才能以這種方式訪問​​國家代碼(烏拉圭 - >「UY」)和緯度和經度值質心部分?看來,這些屬性是與json_decode :( – VORiAND

+0

@VORiAND他們不一定丟失:)丟失,你可以檢查編輯 – user1978142