【问题标题】:Read XML PHP DOM with XPATH使用 XPATH 读取 XML PHP DOM
【发布时间】: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-&gt;evaluate('//GeocodeResponse/result/geometry/location/lat')
  • 然后呢,做一个 $root = $doc->getElementsByTagName( "lat" ); ???
  • 那么标签的内容就会在$res-&gt;item(0)-&gt;nodeValue,见codepad.org/BtvNEnjl

标签: php xml dom xpath


【解决方案1】:

您可能希望切换到更易于解析的 JSON:

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

$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>';
}

【讨论】:

  • JSON 在带宽和服务器资源上也更轻。
  • 这对Google会更好;)
  • 因为我收到警告:在第 11 行的 /home/content/49/7991949/html/apps/friendlocation/get-city-coordonates.php 中为 foreach() 提供的参数无效
  • 有效,谢谢!所以结论是……就用json就好了,好吗?
  • 可能是错误的搜索查询?你可以随时var_dump($geocodeResponse)查看响应的结构,还有$geocodeResponse['status']应该等于OK
猜你喜欢
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 2016-03-14
  • 2011-12-25
  • 1970-01-01
  • 2016-04-05
  • 2015-09-25
  • 2018-02-19
相关资源
最近更新 更多