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;
?>