2013-06-04 45 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;