标题重写为:"PHP数组中的未定义变量"
P粉432930081
2023-09-05 20:13:14
<p>我试图使用php获取国家代码。我使用以下代码,但是得到了这个警告:</p>
<blockquote>
<p>未定义的索引:country_code</p>
</blockquote>
<pre class="brush:php;toolbar:false;">function getIP($ip) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://ipwho.is/".$ip,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "utf8",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
//print_r($response);
curl_close($curl);
if ($err) {
return "cURL Error #:" . $err;
} else {
return $response;
}
}
function isIndo($ip) {
$ip = getIP($ip);
$info = json_decode($ip, true);
//print_r($info);
if( $info['country_code'] == "ID" ) {
return true;
} else {
return false;
}
}</pre>
<p>哪里出错了?</p>
你尝试过isset()吗?
在访问数组键之前,请尝试检查它是否存在
链接到isset()