dongzhao4036 2014-02-18 20:16
浏览 32
已采纳

通过curl获取用户位置

Im having dificult having users location by Curl.

i have this code :

$ip ='123.125.114.144';
$result ='Unkown' ;
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://www.iptolatlng.com/?ip='.$ip);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$ip_data = curl_exec($ch);
curl_close($ch);

if($ip_data && $ip_data->countryFullName != null)  //---the error is in this line
{
    $result = $ip_data->countryFullName;
}

echo $result;

However im getting this error:

Notice: Trying to get property of non-object in /mywebsite/index.php on line 29 Unknown

for testing purpose this is their link with random ip http://www.iptolatlng.com/?ip=123.125.114.144

any help will be much apreciated on whats going wrong.

  • 写回答

1条回答 默认 最新

  • dongmeng4742 2014-02-18 20:26
    关注

    curl_exec returns the result of the request in type of string, while you are trying access the result value in type of object. Because your request returns json string, you should use the function json_decode.

    Example:

    $ip_data = curl_exec($ch);
    $ip_obj = json_decode($ip_data);
    echo $ip_obj->countryFullName;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?