我想确定在文本框中输入的城市用户是否有效,我在下面有以下代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$check = checkCityOrCountry('Sweden');
if($check === false)
echo 'Not Valid country';
else
{
echo 'Valid: <pre>';
print_r($check);
echo '</pre>';
}
function checkCityOrCountry($name)
{
$checkCity = $name;
$checkCity = mb_strtolower($checkCity, "UTF-8");
$countries = vkapi('database.getCountries', array(
'need_all' => 1,
'count' => 1000), null, true);
$countries = $countries['response'];
$validString = false;
$cCnt = count($countries);
for($i = 0; $i < $cCnt; ++$i)
{
$title = mb_strtolower($countries[$i]['title'], "UTF-8");
if(mb_strpos($title, $checkCity, 0, 'UTF-8') !== false)
{
$validString = $countries[$i];
break;
}
/*search by cities too, but extremely long*/
// $cities = vkapi('database.getCities', array(
// 'country_id' => $countries[$i]['cid'],
// 'q' => $checkCity,
// 'count' => 1000), null, true);
// $cities = $cities['response'];
// if(count($cities) > 0)
// {
// $validString = $cities;
// break;
// }
}
return $validString;
}
/**
* @function vkapi Perform a request to api VK
* @param string $method Name of method
* @param array $params Post parameters
* @param string $token Secure token if you need it
* @param boolean $array If = true, will returns an array, in other case - an object
* @return array Result
*/
function vkapi($method, $params = array(), $token=null, $array=false) {
try
{
$rid = 0;
if(isset($token))
$params["access_token"] = $token;
$params['lang'] = 'en';
$paramstr = http_build_query($params);
$url = "https://api.vk.com/method/" . $method . "?" . $paramstr;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
if($array == true)
{
$result = json_decode(json_encode($result), true);
}
return $result;
}
catch(Exception $e)
{
throw new Exception('VK API: '.$e->getMessage());
}
}
?>
</body>
</html>
但无论我输入什么内容,此代码都无效 $ check = checkCityOrCountry(&#39; Sweden&#39;);我总是得到&#34;无效国家&#34;输出
答案 0 :(得分:1)
您可以像这样更新功能:
$check = checkCityOrCountry('Sweden');
echo var_dump($check); // true
$check = checkCityOrCountry('foo');
echo var_dump($check); // false
function checkCityOrCountry($name)
{
$countries = file_get_contents('https://api.vk.com/method/database.getCountries?need_all=1&count=1000&lang=en');
$arr = json_decode($countries, true);
foreach ($arr['response'] as $country) {
if (mb_strtolower($country['title']) === mb_strtolower($name)) {
return true;
}
}
return false;
}
...如果你没有使用cURL的具体原因,只需使用file_get_contents()就更简单了。另外,如果要将数据作为数组处理,使用json_decode(),第二个参数应为“true”。
答案 1 :(得分:0)