[英]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. 如果直接在浏览器上访问http://api.hostip.info/?ip=12.215.42.19 ,我可以看到XML返回,但是当我尝试上述代码时,只有HostipLookupResultSet<br />
被回显。
How do I retrieve the data from this xml? 如何从此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. 我正在尝试类似echo $xml->HostipLookupResultSet->gml:featureMember->Hostip->countryName
但似乎是错误的。
This might work if you query using xpath :- 如果您使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.