将 XML 数据提取到 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16927855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extracting XML data to php
提问by James Paterson
I'm trying to extract data from XML file (http://freegeoip.net/xml/google.com). You can see the content of the file looks something like:
我正在尝试从 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>
I want to take the information stored in the <latitude>
and <longitude>
tags, and store them in separate variables. The problem is, I've little idea how to do this, and was wondering if anyone could show me how to parse XML files with php?
我想获取存储在<latitude>
和<longitude>
标签中的信息,并将它们存储在单独的变量中。问题是,我不知道怎么做,想知道是否有人可以告诉我如何用 php 解析 XML 文件?
回答by Muhammad Saifuddin
$string_data = "<your xml response>";
$xml = simplexml_load_string($string_data);
$latitude = (string) $xml->Latitude;
$longitude = (string) $xml->Longitude;
echo $latitude.' '.$longitude;
回答by Half Crazed
It's easy, use PHP's SimpleXML Library:
很简单,使用 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...
回答by Filippos Karapetis
The PHP manual has a whole section on PHP parsing:
PHP 手册有一整节是关于 PHP 解析的:
For simplicity, you could also use xml_parse_into_struct()
为简单起见,您还可以使用xml_parse_into_struct()
Here's a pretty good example, using SimpleXML:
这是一个很好的例子,使用 SimpleXML: