Extracting XML data to php [duplicate]

拜拜、爱过 提交于 2020-01-28 08:41:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!