首页 文章

带有curl的PHP用于Xml解析

提问于
浏览
0

我正在解析google map api以获取latlong表单地址 . 我成功获得了xml . 如何从xml响应中获取latlong .

我的回答是

SimpleXMLElement对象([status] =>确定[result] => SimpleXMLElement对象([type] =>数组([0] => locality [1] =>政治)[formatted_address] =>新德里,德里,印度[address_component ] =>数组([0] => SimpleXMLElement对象([long_name] =>新德里[short_name] =>新德里[type] =>数组([0] => locality [1] =>政治))[1 ] => SimpleXMLElement对象([long_name] => West Delhi [short_name] => West Delhi [type] => Array([0] => administrative_area_level_2 [1] =>政治))[2] => SimpleXMLElement对象([ long_name] =>德里[short_name] => DL [type] =>数组([0] => administrative_area_level_1 [1] =>政治))[3] => SimpleXMLElement对象([long_name] => India [short_name] = > IN [type] => Array([0] => country [1] => political)))[geometry] => SimpleXMLElement对象([location] => SimpleXMLElement对象([lat] => 28.6353080 [lng] = > 77.2249600)[location_type] => APPROXIMATE [viewport] => SimpleXMLElement对象([southwest] => SimpleXMLEl ement对象([lat] => 28.4010669 [lng] => 76.8396999)[northeast] => SimpleXMLElement对象([lat] => 28.8898159 [lng] => 77.3418146))[bounds] => SimpleXMLElement对象([southwest] = > SimpleXMLElement对象([lat] => 28.4010669 [lng] => 76.8396999)[northeast] => SimpleXMLElement对象([lat] => 28.8898159 [lng] => 77.3418146)))))

我想获得geometry-> location-> lat值

帮助我摆脱这个问题

提前致谢

1 回答

  • 2

    使用DOM XPath更容易,DOMXpath :: evaluate()方法可以从xml中获取标量值:

    $xml = <<<'XML'
    <GeocodeResponse>
     <status>OK</status>
     <result>
      <geometry>
       <location>
        <lat>37.4217550</lat>
        <lng>-122.0846330</lng>
       </location>
       <location_type>ROOFTOP</location_type>
       <viewport>
        <southwest>
         <lat>37.4188514</lat>
         <lng>-122.0874526</lng>
        </southwest>
        <northeast>
         <lat>37.4251466</lat>
         <lng>-122.0811574</lng>
        </northeast>
       </viewport>
      </geometry>
     </result>
    </GeocodeResponse>
    XML;
    
    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    
    $lat = $xpath->evaluate('number(/GeocodeResponse/result/geometry/location/lat)');
    $lng = $xpath->evaluate('number(/GeocodeResponse/result/geometry/location/lng)');
    
    var_dump($lat, $lng);
    

    输出:

    float(37.421755)
    float(-122.084633)
    

相关问题