1

我正在尝试从 XML 文件 ( http://freegeoip.net/xml/google.com ) 中提取数据。您可以看到文件的内容类似于:

<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>and<longitude>标记中的信息,并将它们存储在单独的变量中。问题是,我不知道该怎么做,想知道是否有人可以告诉我如何用 php 解析 XML 文件?

4

3 回答 3

9
$string_data = "<your xml response>";
$xml = simplexml_load_string($string_data);
$latitude = (string) $xml->Latitude;
$longitude = (string) $xml->Longitude;
echo $latitude.' '.$longitude;
于 2013-06-04T21:40:23.793 回答
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...
于 2013-06-04T21:38:03.977 回答
2

PHP 手册有一整节关于 PHP 解析:

为简单起见,您还可以使用xml_parse_into_struct()

这是一个非常好的示例,使用 SimpleXML:

http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

于 2013-06-04T21:37:17.853 回答