2011-11-03 82 views
0

我有一個問題。使用XPATH讀取XML PHP DOM

我有XML

http://maps.googleapis.com/maps/api/geocode/xml?address=new+york&sensor=true

我想從例如讀取

GeocodeResponse /結果/幾何形狀/位置/ LAT

GeocodeResponse /結果/幾何/ location/lng

也許使用XPATH,這是我迄今爲止...

<?php 

$Address = "new+york"; 
$Query = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true"; 
$XmlResponse = file_get_contents($Query); 

$doc = new DOMDocument(); 
$doc->loadXML($XmlResponse); 

$root = $doc->getElementsByTagName("GeocodeResponse"); 
foreach($root as $val) 
{ 
    $hrefs = $val->getElementsByTagName("status"); 
    $status = $hrefs->item(0)->nodeValue; 

    foreach($hrefs as $val2) 
    { 
     $hrefs2 = $val2->getElementsByTagName("type"); 
     $type = $hrefs2->item(0)->nodeValue; 

     echo "Type is: $type <br>"; 
    } 

    echo "Status is: $status <br>"; 
} 


?> 

我可以有一些建議?

也許我可以用

$xpath = new DOMXPath($xml); 
$hrefs = $xpath->evaluate("/page"); 

更新!

我設法得到這個結果...

$xpath = new DOMXPath($doc); 
$res = $xpath->evaluate('//GeocodeResponse/result/geometry'); 

$root = $doc->getElementsByTagName("location"); 
foreach($root as $val) 
{ 
    $hrefs = $val->getElementsByTagName("lat"); 
    $status = $hrefs->item(0)->nodeValue; 

    echo "Status is: $status <br>"; 
} 

,但我想沒有的foreach像

$xpath = new DOMXPath($doc); 
$res = $xpath->evaluate('//GeocodeResponse/result/geometry'); 
$hrefs = $val->getElementsByTagName("lat"); 
$status = $hrefs->item(0)->nodeValue; 

echo "Status is: $status <br>"; 

這可能嗎?

+0

問題是什麼?什麼不行? –

+0

我不知道如何繼續下去,直到我到達GeocodeResponse/result/geometry/location/lng – Master345

+1

您必須創建一個新的DOMXPath對象:'$ xpath = new DOMXPath($ xml)'。然後你必須評估你的XPath表達式:'$ res = $ xpath-> evaluate('// GeocodeResponse/result/geometry/location/lat')' – ComFreek

回答

1

您可能想要切換到JSON是更容易解析:

http://maps.googleapis.com/maps/api/geocode/JSON地址=新+紐約&傳感器=真

$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=new+york&sensor=true'); 

$geocodeResponse = json_decode($json, true); 

foreach($geocodeResponse['results'] as $result){ 
    echo $result['geometry']['location']['lat'].', '.$result['geometry']['location']['lng'] .'<br>'; 
} 
+2

JSON在帶寬和服務器資源方面也較輕。 –

+0

嗯,我從來沒有與JSON合作,它的方式更好,然後XML? – Master345

+2

這會更好的**你**和**谷歌**;) – ComFreek