0

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.

3 Answers 3

3

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]');
Sign up to request clarification or add additional context in comments.

Comments

1

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";
}

Comments

0
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.