如何从PHP中的ipinfo.io获取位置?

Cod*_*ien 6 php api json

我正在使用ipinfo.io来使用PHP获取我当前的城市(位置).

但是,在使用这段代码时,我无法看到我的城市.

$ipaddress = $_SERVER["REMOTE_ADDR"];

function ip_details($ip) {
    $json = file_get_contents("http://ipinfo.io/{$ip}/geo");
    $details = json_decode($json);
    return $details;
}

$details = ip_details($ipaddress);
echo $details->city;
Run Code Online (Sandbox Code Playgroud)

我不知道错误在哪里.

Oct*_*tal 5

function getClientIP(){
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  }
  return $ip;
}

$ipaddress = getClientIP();

function ip_details($ip) {
  $json = file_get_contents("http://ipinfo.io/{$ip}/geo");
  $details = json_decode($json, true);
  return $details;
}

$details = ip_details($ipaddress);
echo $details['city'];
Run Code Online (Sandbox Code Playgroud)

这应该工作.

但是,如果你想要一个在线资源,我建议你习惯使用curl而不是file_get_contents()./sf/answers/386586791/