使用函数卷曲 returns 什么都没有,但在终端中卷曲 returns json 对象。如何调试?

Curl returns nothing with a function, but returns json object in terminal. How to debug?

这是我试图从中获取内容的 URL:

$url = 'http://mgcash.com/api/?a=get_offers&key=13658244dad4cfb3&country=US&ua=Mozilla/5.0%20%28Macintosh;%20Intel%20Mac%20OS%20X%2010.10;%20rv:35.0%29%20Gecko/20100101%20Firefox/35.0&format=json';

所以我尝试了 file_get_contents(),那个工作正常。然后我尝试了这个一直有效的功能,但在这种情况下无效。

class SimpleCurl 
{

    public static function get($url, $params=array()) 
    {
        $url = $url . '?' . http_build_query($params, '', '&');
        $ch = curl_init();

        $options = [
            CURLOPT_URL             => $url,
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_CONNECTTIMEOUT  => 10,
            CURLOPT_SSL_VERIFYPEER  => false
        ];
        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

}

然后我尝试通过以下命令使用终端:

curl -X GET "http://mgcash.com/api/?a=get_offers&key=13658244dad4cfb3&country=US&ua=Mozilla/5.0%20%28Macintosh;%20Intel%20Mac%20OS%20X%2010.10;%20rv:35.0%29%20Gecko/20100101%20Firefox/35.0&format=json"

这奏效了。它返回了正确的 JSON 对象,没有任何问题。 任何人都可以让我知道你如何调试 CURL 并弄清楚这里的问题是什么?

经过进一步测试和调试后,我注意到以下内容。由于我的项目需要 JSON 对象,所以我将获取的 CURL $content 传递给 $json_data = json_decode($content); 并且它 returns 什么也没有。空白!

但是如果我在它进入 json_decode() 之前尝试 echoprint_r,我实际上得到了一些 RAW information/text 而不是 JSON 对象.什么...

你应该使用CURLOPT_VERBOSE来输出调试信息:

CURLOPT_VERBOSE - TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

尽管如果您 运行 在浏览器中运行脚本,您不会看到详细的日志,因为默认情况下它会将所有信息输出到 stderr(通常输出可以是在你的 error.log).

中看到

因此,要查看记录的信息,您应该在终端中查看 error.log、运行 脚本,或者为 cURL 提供另一个文件处理程序以输出日志。在最简单的情况下,您可以将输出重定向到 stdout,如下所示:

$options = [
    CURLOPT_VERBOSE => true,
    CURLOPT_STDERR => fopen('php://stdout', 'w'),
    ...
];

在这种情况下,您会在浏览器中看到您的登录信息。或者,您可以向 fopen 提供任何其他文件名以将日志输出到文件中。

参考:http://php.net/manual/en/function.curl-setopt.php

您没有将 $params 传递给 get 函数,而您的 $url 最终变成了 http://mgcash.com/api/?a=get_offers&key=13658244dad4cfb3&country=US&ua=Mozilla/5.0%20%28Macintosh;%20Intel%20Mac%20OS%20X%2010.10;%20rv:35.0%29%20Gecko/20100101%20Firefox/35.0&format=json?注意附加的 ?

您可以将 get 函数更改为仅在 $params 不为空时连接查询字符串,如下所示:

...
if (!empty($params)){     
   $url = $url . '?' . http_build_query($params, '', '&');
}