2013-06-04 46 views
0

我試圖從XML文件中提取數據(http://freegeoip.net/xml/google.com)。你可以看到文件的內容看起來是這樣的:將XML數據提取到php

<Response> 
<Ip>74.125.235.3</Ip> 
<CountryCode>US</CountryCode> 
<CountryName>United States</CountryName> 
<RegionCode>CA</RegionCode> 
<RegionName>California</RegionName> 
<City>Mountain View</City> 
<ZipCode>94043</ZipCode> 
<Latitude>37.4192</Latitude> 
<Longitude>-122.0574</Longitude> 
<MetroCode>807</MetroCode> 
<AreaCode>650</AreaCode> 
</Response> 

我想利用存儲在<latitude><longitude>標籤中的信息,並將其存儲在獨立的變量。問題是,我不知道如何做到這一點,並想知道是否有人可以告訴我如何用PHP解析XML文件?

回答

3

這很容易,使用PHP的SimpleXML庫:

$xml = simplexml_load_file("http://freegeoip.net/xml/google.com"); 
echo $xml->Ip; // 173.194.38.174 
echo $xml->CountryCode; // US 
echo $xml->ZipCode; // 94043 
// etc... 
5
$string_data = "<your xml response>"; 
$xml = simplexml_load_string($string_data); 
$latitude = (string) $xml->Latitude; 
$longitude = (string) $xml->Longitude; 
echo $latitude.' '.$longitude;