2012-02-09 83 views
-1

我有一个xml feed,我需要从中访问一个元素。但是,我尝试过的方法都没有奏效。如何从PHP中的XML文件读取元素?

下面是完整的XML提要:

<GeocodeResponse> 
<status>OK</status> 
<result> 
    <type>locality</type> 
    <type>political</type> 
    <formatted_address>Liverpool, Merseyside, UK</formatted_address> 
    <address_component> 
     <long_name>Liverpool</long_name> 
     <short_name>Liverpool</short_name> 
     <type>locality</type> 
     <type>political</type> 
    </address_component> 
    <address_component> 
     <long_name>Merseyside</long_name> 
     <short_name>Mersyd</short_name> 
     <type>administrative_area_level_2</type> 
     <type>political</type> 
    </address_component> 
    <address_component> 
     <long_name>England</long_name> 
     <short_name>England</short_name> 
     <type>administrative_area_level_1</type> 
     <type>political</type> 
    </address_component> 
    <address_component> 
     <long_name>United Kingdom</long_name> 
     <short_name>GB</short_name> 
     <type>country</type> 
     <type>political</type> 
    </address_component> 
    <geometry> 
     <location> 
      <lat>53.4115400</lat> 
      <lng>-2.9901160</lng> 
     </location> 
     <location_type>APPROXIMATE</location_type> 
     <viewport> 
      <southwest> 
       <lat>53.3049930</lat> 
       <lng>-3.2462348</lng> 
      </southwest> 
      <northeast> 
       <lat>53.5178208</lat> 
       <lng>-2.7339972</lng> 
      </northeast> 
     </viewport> 
     <bounds> 
      <southwest> 
       <lat>53.3115426</lat> 
       <lng>-3.0191794</lng> 
      </southwest> 
      <northeast> 
       <lat>53.5039071</lat> 
       <lng>-2.8115043</lng> 
      </northeast> 
     </bounds> 
    </geometry> 
</result> 
</GeocodeResponse> 

我想选择的几何性质 - >位置 - > LAT->的位置,然后在这个纬度和经度。

+0

( http://php.net/manual/en/book.xml.php) – 2012-02-09 22:32:38

+1

这里有一个PHP的问题吗?有任何代码?你如何阅读文件?你说什么都没有奏效 - 但是你尝试了什么? – 2012-02-09 22:32:52

+3

可能重复的[如何在PHP中解析XML文件](http://stackoverflow.com/questions/1706042/how-to-parse-xml-file-in-php) – 2012-02-09 22:35:00

回答

2

你试过simplexml_load_stringsimplexml_load_file? 只需用它加载数据,然后访问你想要的节点,就像这样:

$xml = simplexml_load_file('your.xml'); 
echo $xml->GeocodeResponse->result->geometry->location->lat; 
echo $xml->GeocodeResponse->result->geometry->location->lon; 
+0

对不起,我应该有更具体的 我得到一个错误,但似乎是由现在,因为它是我的简单的xml加载程序不工作。我在php.ini中打开了openssl,一切都很顺利。 ]]对不起浪费每个人的时间我有+所有评论。谢谢 – 2012-02-09 22:45:40

+0

@DanielBenzie请用这个信息更新你的问题,没有所有适当的细节,我们将无法得出一个很好的答案。 – Oldskool 2012-02-09 22:48:24

0

如果你有一个字符串,你可以这样做:[!XML解析器救援]

$str = "<?xml version='1.0'?> 
      <document> 
       <cmd>login</cmd> 
       <login>Richard</login> 
      </document>"; 
$xml = simplexml_load_string($str); 

print_r($xml); 

print_r($xml->document->cmd); 

// Remember to type cast it a string if you want the actual value. 
// Example: 
$myval = (string) $xml->document->cmd;