【发布时间】:2011-12-21 12:37:43
【问题描述】:
我有一个问题。
我有xml
http://maps.googleapis.com/maps/api/geocode/xml?address=new+york&sensor=true
我想阅读示例
GeocodeResponse/result/geometry/location/lat
和
GeocodeResponse/result/geometry/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 之前,我不知道如何走得更远
-
你必须创建一个新的 DOMXPath 对象:
$xpath = new DOMXPath($xml)。然后你必须评估你的 XPath 表达式:$res = $xpath->evaluate('//GeocodeResponse/result/geometry/location/lat') -
然后呢,做一个 $root = $doc->getElementsByTagName( "lat" ); ???
-
那么标签的内容就会在
$res->item(0)->nodeValue,见codepad.org/BtvNEnjl