2012-02-09 23 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;