我有一個問題。使用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>";
這可能嗎?
問題是什麼?什麼不行? –
我不知道如何繼續下去,直到我到達GeocodeResponse/result/geometry/location/lng – Master345
您必須創建一個新的DOMXPath對象:'$ xpath = new DOMXPath($ xml)'。然後你必須評估你的XPath表達式:'$ res = $ xpath-> evaluate('// GeocodeResponse/result/geometry/location/lat')' – ComFreek