从谷歌地图api解析xml数据

时间:2013-05-08 23:45:14

标签: php xml google-maps-api-3

我必须仅使用指定坐标从xml数据中获取方向信息。这是我的代码

    <?php 
$string= simplexml_load_file("http://maps.googleapis.com/maps/api/directions/xml?origin=37.036543,35.288086&destination=36.997415,35.288067&sensor=false");
    print_r ($string);
    $xml = new SimpleXMLElement($string);

    $result = $xml->xpath('/WebServiceRequest/result[2]/message/text()');

    while(list( , $node) = each($result)) {
        echo 'b/c: ',$node,"\n";
    }
    ?>

但是我收到以下错误:  警告:SimpleXMLElement :: __ construct()[simplexmlelement .-- construct]:实体:第4行:解析器错误:期望开始标记,'&lt;'

中找不到

当然还有其他错误。

1 个答案:

答案 0 :(得分:0)

您可以在下面执行。您编写的xpath我在Google的响应XML中找不到类似的内容。所以我根据收到Google的回复给出了提示。我假设您需要<step>元素及其子元素来实现/解决您的要求。在下面,您可以根据您的进一步要求进行必要的更改,以下内容已准备就绪。

我还将print_r($item)用于您的调试目的。所以也看看它。

<?php 
$xml = simplexml_load_file("http://maps.googleapis.com/maps/api/directions/xml?origin=37.036543,35.288086&destination=36.997415,35.288067&sensor=false");
$result = $xml->xpath('//step');

foreach($result as $item){
    //echo "<pre>";print_r($item);
    echo "travel_mode::".$item->travel_mode;
    echo "<br/>start_location::";
        //child elements of start_location element
        foreach($item->start_location as $child)
        {
            echo "<br/>lat::".$child->lat;
            echo "<br/>lng::".$child->lng;
        }
        //like above you can get other elements as well their child elements too.
    echo "<hr/>";
}
?>