简体   繁体   中英

json_decode return null i guess

I try to run this on my server:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $ip;
$city = $details -> city;
echo $city;
?>

But, this print ip only. Maybe a server problem or configuration?

You need to code a bit more defensively, if that site has no data for the ip address you give it, then it wont return any city property

This is a little safer

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $ip . ' ';
if (isset($details->city)){
    echo $details->city;
} else {
    echo 'data not available';
}

Judging from what it returned for my IP Address, the details it provides are not very accurate anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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