【问题标题】:json_decode is returning a null object after I use CURL to obtain JSON datajson_decode 在我使用 CURL 获取 JSON 数据后返回一个空对象
【发布时间】:2013-02-16 01:59:34
【问题描述】:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
var_dump($output);
$json_array = json_decode($output, true);

var_dump(curl_error($ch));

curl_close($ch);

var_dump($json_array);

$output 的 VARDUMP

string(267) "HTTP/1.1 200 OK 日期:2013 年 3 月 1 日星期五 14:16:57 GMT 服务器:Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7 X-Powered- By: PHP/5.4.7 缓存控制: no-cache x-debug-token: 5130b85a178bd 传输编码: 分块内容类型: application/json {"name":"manoj"}"

curl_error($ch) 的 VARDUMP

字符串(0) ""

$json_array 的 VARDUMP

【问题讨论】:

  • 您的输出是所有带有标题的内容,尽管它不是有效的 JSON。

标签: php json curl


【解决方案1】:

如果出于任何原因您必须维护 CURLOPT_HEADER 选项,您可以使用以下内容:

$output = curl_exec($ch);  

$json_data = mb_substr($output, curl_getinfo($ch, CURLINFO_HEADER_SIZE));  
$data = json_decode($json_data);

您可以使用 CURLOPT_HEADER 选项检查返回码 200、404 等...

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

【讨论】:

    【解决方案2】:

    如果无法解码json,则返回NULL

    您不想在 curl_exec 的正文中返回标头,因此您需要:

    curl_setopt($ch, CURLOPT_HEADER, false)
    

    http://php.net/manual/en/function.json-decode.php

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-02
    • 2015-11-10
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多