我正在構建可以利用多個Web服務進行地理編碼的Geocoding類(即Google,Yahoo,Bing等)。我試圖用這種方式來實現新的web服務可以很容易地配置。大多數Web服務返回XML/JSON ..對於PHP,我選擇XML作爲我的主要焦點。所有的代碼已經到位,但現在谷歌,例如返回以下XML(轉化爲simple_xml_element)動態訪問嵌套對象
SimpleXMLElement Object
(
[status] => OK
[result] => Array
(
[0] => SimpleXMLElement Object
(
[type] => postal_code
[formatted_address] => 1010 Lausanne, Switzerland
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => 1010
[short_name] => 1010
[type] => postal_code
)
[1] => SimpleXMLElement Object
(
[long_name] => Lausanne
[short_name] => Lausanne
[type] => Array
(
[0] => locality
[1] => political
)
)
[2] => SimpleXMLElement Object
(
[long_name] => Vaud
[short_name] => VD
[type] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[3] => SimpleXMLElement Object
(
[long_name] => Switzerland
[short_name] => CH
[type] => Array
(
[0] => country
[1] => political
)
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 46.5376186
[lng] => 6.6539665
)
[location_type] => APPROXIMATE
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 46.5253574
[lng] => 6.6384420
)
[northeast] => SimpleXMLElement Object
(
[lat] => 46.5467887
[lng] => 6.6745222
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 46.5253574
[lng] => 6.6384420
)
[northeast] => SimpleXMLElement Object
(
[lat] => 46.5467887
[lng] => 6.6745222
)
)
)
)
)
我需要的信息是在[位置]標籤,所以我試圖存儲路徑在VAR:
$lat_path = 'result[0]->geometry->location->lat;
,然後嘗試這種方式訪問該值:
(suppose $xml is the object)
$xml->{$lat_path};
但這好好嘗試的工作。有沒有什麼辦法可以基於動態或變量來訪問信息。我不想用Google特定的代碼破壞我的地理編碼方法。
謝謝!
使用[SimpleXMLElement :: xpath](http://www.php.net/manual/simplexmlelement.xpath.php)代替php異議符號。 (如果你可以顯示一些xml,我會嘗試提供一個示例實現) – Yoshi
您可以爲此編寫方法並忘記.. – Vytautas
我也嘗試使用Xpath,但它沒有工作:( print_r $ xml-> Xpath('geometry/location'));給了我一個空數組。 –