dslpofp041310584 2017-11-01 19:50
浏览 240

无法将Curl输出转换为JSON

Time for a second set of eyes. I've been looping on this for awhile. The url http://freegeoip.net/json/ appears to return JSON. I can't seem to decode or parse it. Any help would be greatly appreciated. Code follows:

    <?php

    //////////////////////////////////////////////////////////////////////
    //  Debug options
    //////////////////////////////////////////////////////////////////////
     error_reporting(E_ALL);
     error_reporting(E_ALL | E_STRICT);
     ini_set('display_errors', 1);

    function get_ip_address()
    {
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
            if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                return $ip;
            }
            }
        }
        }
    }

    $myIP = get_ip_address();

    $url = "http://freegeoip.net/json/" . $myIP;
    $cURL = curl_init();
    curl_setopt($cURL, CURLOPT_URL, $url);
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cURL, CURLOPT_HTTPGET, true);
    curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json'
    ));

    $result = curl_exec($cURL);
    $myArray = json_decode($result);

    curl_close($cURL);

    //////////////////////////////////////////////////////////////////////
    //  Debug  
    //////////////////////////////////////////////////////////////////////
     echo $myArray->region_code . "<br />";
     echo $myArray->region_name . "<br />";
     echo $myArray->city . "<br />";
     echo $myArray->zip_code . "<br />";
     echo $myArray->time_zone . "<br />";
     echo $myArray->latitude . "<br />";
     echo $myArray->longitude . "<br />";
     echo $myArray->metro_code . "<br />";
  • 写回答

1条回答

  • dtotuki47568 2017-11-01 20:02
    关注

    Edit : Removed answer.

    I put the code into my server and it works perfectly fine for me.

    Maybe curl is disabled on his server?

    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘