简体   繁体   中英

How to parse XML using PHP

I've this code

$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child) {
    echo $child->getName() . ": " . $child . "<br />";
}

If I visit http://api.hostip.info/?ip=12.215.42.19 directly on the browser, I can see the XML return but when I tried the above code, only HostipLookupResultSet<br /> gets echoed.

How do I retrieve the data from this xml? I'm interested in getting coutry and country abbreviation.

I was trying something like echo $xml->HostipLookupResultSet->gml:featureMember->Hostip->countryName but it seems it is wrong.

This might work if you query using xpath :-

// optional for register namespace into xpath
$xml->registerXPathNamespace('gml', 'http://www.opengis.net/gml');

$result = $xml->xpath('//*[self::countryName or self::countryAbbrev]');

You need to add the namespace. See the code bellow

/* @var $xml SimpleXMLElement */
echo $xml->getName() . "\n";
$namespaces = $xml->getDocNamespaces();

foreach($xml->children($namespaces['gml']) as $child) {
    echo $child->getName() . ": " . $child . "\n";
}
You can try the following code for getting Country and Country Abbrevation:


$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
$cntry= $xml->xpath('//gml:featureMember');

foreach($cntry as $child) {
    echo $child->Hostip->countryName;
echo "<br />";
echo $child->Hostip->countryAbbrev;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM