1

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
James Paterson
  • 2,652
  • 3
  • 27
  • 40

3 Answers3

9
$string_data = "<your xml response>";
$xml = simplexml_load_string($string_data);
$latitude = (string) $xml->Latitude;
$longitude = (string) $xml->Longitude;
echo $latitude.' '.$longitude;
Muhammad Saifuddin
  • 1,284
  • 11
  • 29
3

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...
Rob W
  • 9,134
  • 1
  • 30
  • 50
2

The PHP manual has a whole section on PHP parsing:

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

Filippos Karapetis
  • 4,367
  • 21
  • 39