【问题标题】:What's wrong with this php json script? [duplicate]这个 php json 脚本有什么问题? [复制]
【发布时间】:2012-09-22 11:52:21
【问题描述】:

可能重复:
How to get useful error messages in PHP?

我无法让这个 php json 脚本工作。我正在尝试使用他们的 api 从 twitter 获取屏幕名称。

这就是我所做的。

$send_request = file_get_contents('https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey');

$request_contents = json_decode($send_request);

echo $request_contents->screen_name;

为什么每次都返回一个空白值?我试过在这里和那里改变一些东西,但它不起作用......

【问题讨论】:

  • @hakre 虽然该问题的答案将有助于解决这个问题,但它们几乎不是重复的。按照这种逻辑,每个涉及 PHP 错误的问题都是该问题的副本。

标签: php json api twitter scripting


【解决方案1】:

尝试使用

print_r($request_contents); 

var_dump($request_contents); 

用于检查数组。

【讨论】:

    【解决方案2】:

    您的页面不应为空白.. 您应该收到类似 Notice: Trying to get property of non-object in 的错误,因为您正在调用无效的 $request_contents->screen_name

    尝试告诉 PHP 输出所有错误使用

    error_reporting(E_ALL);
    

    我也更喜欢 CURL 更快

    $ch = curl_init("https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $request_contents = json_decode($result);
    var_dump($request_contents[0]->screen_name);
    

    输出

     string 'frankmeacey' (length=11)
    

    【讨论】:

      【解决方案3】:

      这是

      $request_contents[0]->screen_name
      

      因为 $request_contents 是一个对象数组,而不是对象本身。

      做一个

      var_dump($request_contents);
      

      查看 json 的结构。

      【讨论】:

        【解决方案4】:

        该数据看起来是数组中的一个对象。试试

        echo $request_contents[0]->screen_name;
        

        最好先检查它是一个数组并从中获取第一个用户:

        if (is_array($request_contents)) {
            $user_info = $request_contents[0];
        }
        
        if (isset($user_info)) {
            echo $user_info->screen_name;
        }
        

        【讨论】:

          【解决方案5】:

          因为你得到的数据结构是一个对象数组,而不是一个对象。

          echo $request_contents[0]->screen_name;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-09-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-27
            相关资源
            最近更新 更多