我有以下脚本在 hostip.info 上使用api。该页面根据IP地址解析用户位置的xml读数。在我的功能中,一切都在工作,除了城市。
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$city_match);
我已将其缩小到preg_match
错误但我不确定如何修复它。以下是xml输出示例:http://api.hostip.info/?ip=12.215.42.19
<?php
function getCountryCity()
{
if(isset($_SERVER['REMOTE_ADDR']) && strlen($_SERVER['REMOTE_ADDR']) > 0) {
$ipAddr = $_SERVER['REMOTE_ADDR'];
// verify the IP address
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array();
// get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);
// get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$city_match);
$ipDetail['city'] = $city_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("@<countryName>(.*?)</countryName>@si",$xml,$country_match);
$ipDetail['country'] = $country_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
$ipDetail['country_code'] = $cc_match[1];
// return the array containing city, country and country code
return $ipDetail;
} else {
return false;
}
}
$ipDetail = getCountryCity();
$user_city = $ipDetail['city'];
$user_country = $ipDetail['country'];
$user_cc = $ipDetail['country_code'];
echo $user_country.' ('.$user_cc.')';
echo $user_city;
?>
答案 0 :(得分:1)
$xml = new SimpleXMLElement($yourXML);
$user_city = $xml->xpath('//gml:name/text()');
$user_country= $xml->xpath('//countryName/text()');
$cc= $xml->xpath('//countryAbbrev/text()');
我发现XPATH查询比RegEx更容易编写。
很抱歉,这不能直接回答您的问题。试图发表评论,但格式化完全搞砸了
答案 1 :(得分:1)
preg_match_all("@<gml:name>(.*?)</gml:name>@si",$xml,$city_match);
只需删除<Hostip>(\s)*
并使用preg_match_all即可获取所有标记。然后你可以在数组中选择一个。
答案 2 :(得分:0)
function getCountryCity() {
if(isset($_SERVER['REMOTE_ADDR']) && strlen($_SERVER['REMOTE_ADDR']) > 0) {
$user_ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents('http://api.hostip.info/?ip='.$user_ip);
$user_details = array();
$xml = new DOMDocument();
$xml->loadXml($response);
$xpath = new DOMXpath($xml);
$path = '/HostipLookupResultSet/gml:featureMember/Hostip/';
// create values for array
$ip = $xpath->evaluate($path . 'ip')->item(0)->nodeValue;
$city = $xpath->evaluate($path . 'gml:name')->item(0)->nodeValue;
$countryName = $xpath->evaluate($path . 'countryName')->item(0)->nodeValue;
$countryAbbrev = $xpath->evaluate($path . 'countryAbbrev')->item(0)->nodeValue;
// assign values to array
$user_details['ip'] = $ip;
$user_details['city'] = $city;
$user_details['countryName'] = $countryName;
$user_details['countryAbbrev'] = $countryAbbrev;
return $user_details;
} else {
return false;
}
}