简体   繁体   English

PHP比较字符串-IP地址和固定值的国家/地区

[英]PHP compare strings - country from IP address and fixed value

I have this php which determines the country from IP address, that part works. 我有这个PHP,它从IP地址确定国家,那部分工作。 It is then supposed to say "hello UK" if the country = "United Kingdom" however it returns "not uk" even though when I echo the $location value it says United Kingdom. 然后,如果国家=“英国”,则应该说“ hello UK”,但是即使我回显$ location值时它也返回“ not uk”,但它表示英国。

I wondered if it was due to the variable type but I did echo gettype ($location); 我想知道这是否是由于变量类型引起的,但我确实做了echo gettype($ location); and it returned string, I believe I am comparing it to a string and cannot now work out why I get the unexpected result. 并且返回了字符串,我相信我正在将其与字符串进行比较,现在无法弄清为什么我得到了意外的结果。

What is wrong with my php comparison? 我的php比较有什么问题?

Thanks 谢谢

$IP = "{$_SERVER['REMOTE_ADDR']}";  
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$IP)) ;
$location = $query ['country'];
echo $location;
if  ($location == 'United Kingdom') {
echo 'hello UK';
}else{
echo 'not uk';}

Your example code works for me, but you should make sure you trim any whitespace surrounding the country name before doing the comparison:- 您的示例代码对我有用,但是在进行比较之前,请确保修剪国名周围的空白:

trim($country) === 'United Kingdom'

It might also be worth checking against a lowercase string too:- 也可能还需要检查小写字符串:-

strtolower(trim($country)) === 'united kingdom'

If that's still not working use var_dump() rather than echo to check the value, that should make any inconsistencies more obvious as it will show the string in quotes:- 如果仍然无法使用,请使用var_dump()而不是echo来检查值,这将使任何不一致性更加明显,因为它将在引号中显示字符串:

var_dump($country);

Use === when evaluating a string to string comparison, which is what this is. 在评估字符串与字符串的比较时,请使用===

However it sounds to me that $location is not equal to "United Kingdom" when it runs the check. 但是,在我看来,$ location运行支票时不等于“ United Kingdom”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM