问题
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:
<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?
回答1:
$string_data = "<your xml response>";
$xml = simplexml_load_string($string_data);
$latitude = (string) $xml->Latitude;
$longitude = (string) $xml->Longitude;
echo $latitude.' '.$longitude;
回答2:
It's easy, use PHP's SimpleXML Library:
$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...
回答3:
The PHP manual has a whole section on PHP parsing:
- http://php.net/manual/en/book.simplexml.php
- http://php.net/manual/en/book.xml.php
For simplicity, you could also use xml_parse_into_struct()
Here's a pretty good example, using SimpleXML:
http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
来源:https://stackoverflow.com/questions/16927855/extracting-xml-data-to-php