我正在寻找一种明确的方式来检测访客是否来自中东。如果是的话,我需要显示一个不同的标题图像(当前的标题图像中有一个标题,所以它是不受欢迎的。)
我可以编写if then else,但我只是想找一个简单的函数来检测。以下是我用IP获取国家的功能:
function get_country_by_ip($ip){
if(!$ip) return false; # Missing parameter
# Pull the XML
$url = 'http://api.hostip.info/?ip='.$ip;
$xml = simplexml_load_file($url);
# Parse the data and store into array
$citystate = explode(", ", $xml->children('gml', true)->featureMember->children()->Hostip->children('gml', true)->name);
$result['city'] = $citystate[0];
$result['state'] = $citystate[1];
$result['country'] = $xml->children('gml', true)->featureMember->children()->Hostip->countryName;
$result['country_abbr'] = $xml->children('gml', true)->featureMember->children()->Hostip->countryAbbrev;
return (object) $result;
}
有人可以帮忙吗?感谢。
答案 0 :(得分:2)
您可以定义哪些国家属于“中东”组 - 通过直接在PHP文件或数据库中定义可配置数组,然后检查您的函数返回的给定国家/地区是否属于“属于”的国家/地区列表中东”。通过你的例子,像这样:
$middleEast = array(
'Syria',
'Iraq',
... // all the rest
);
$country = get_country_by_ip($ip);
if (in_array($country['country'], $middleEast) {
echo 'Middle East!';
exit;
}
答案 1 :(得分:1)
<?php
/* get country by ip */
function get_country_by_ip($ip){
if(!$ip) return false;
/* pull the xml */
$url = 'http://api.hostip.info/?ip='.$ip;
$xml = simplexml_load_file($url);
/* parse the data and store into array */
$citystate = explode(", ", $xml->children('gml', true)->featureMember->children()->Hostip->children('gml', true)->name);
$result['city'] = $citystate[0];
$result['state'] = $citystate[1];
$result['country'] = (array) $xml->children('gml', true)->featureMember->children()->Hostip->countryName;
$result['country'] = $result['country'][0];
$result['country_abbr'] = (array) $xml->children('gml', true)->featureMember->children()->Hostip->countryAbbrev;
$result['country_abbr'] = $result['country_abbr'][0];
return (object) $result;
}
/* get country */
$geo_info = get_country_by_ip($_SERVER['REMOTE_ADDR']);
/* MENA countries */
$mena = array(
'ALGERIA',
'BAHRAIN',
'EGYPT',
'IRAN',
'IRAQ',
'ISRAEL',
'JORDAN',
'KUWAIT',
'LEBANON',
'LIBYA',
'MOROCCO',
'OMAN',
'PALESTINE',
'QATAR',
'SAUDI ARABIA',
'SYRIA',
'TUNISIA',
'UNITED ARAB EMIRATES',
'YEMEN',
'ARMENIA',
'AZERBAIJAN',
'CYPRUS',
'DJIBOUTI',
'MALTA',
'MAURITANIA',
'SAHRAWI ARAB DEMOCRATIC REPUBLIC',
'SOMALIA',
'SUDAN',
'TURKEY',
);
/* image with a hog */
$img = 'mmm-pork.jpg';
if(in_array($geo_info->country, $mena)){
/* image with no hog */
$img = 'cant-have-pork.jpg';
} ?>
答案 2 :(得分:0)