Getting information from xml php
I'm creating a script that will take users location from their ip. I saw this api.But know idea how i can get them in array and print them.
Here is a sample link: http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true
This a sample respones
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName&g开发者_Python百科t;
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<TimezoneName>America/Los_Angeles</TimezoneName>
<Gmtoffset>-25200</Gmtoffset>
<Isdst>1</Isdst>
</Response>
How do i get the information from this in an array and print?
Use a SimpleXml instance and loop through all the children nodes
$url = 'http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true';
$xml = new SimpleXmlElement($url, null, true);
$info = array();
foreach ($xml->children() as $child) {
$name = $child->getName();
$info[$name] = $xml->$name;
}
// info['Ip'] = '74.125.45.100', etc
You should look into simpleXML (http://php.net/manual/en/book.simplexml.php)
Using simpleXML you could do something like:
$xml = simplexml_load_file($xmlFile,'SimpleXMLElement', LIBXML_NOCDATA);
$ip = (string) $xml->Ip;
$status = (string) $xml->Status;
Look at SimpleXML, it's the easiest way to parse XML with PHP.
精彩评论