【问题标题】:json_decode equals to nulljson_decode 等于 null
【发布时间】:2015-12-01 20:27:38
【问题描述】:

如何获得更好的错误消息来调试我的问题?

<?php

// Setup cURL
$ch = curl_init('http://api.mirai.so/external/test');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    echo "Error!";
}
else {
$result = var_dump(json_decode($response, TRUE));
echo $result;
}
?>

它应该做的是从 .json 文件中获取数据并回显它们。

【问题讨论】:

  • var_dump 返回 null。
  • 您可能需要检查 json_last_error() php.net/manual/en/function.json-last-error.php 和 curl_error 的状态。 var_dump 应该打印解码 json 对象的输出。如果您没有看到任何内容,则可能是您的系统中存在上游错误。
  • 如果在浏览器中运行 api 会发生什么?你得到什么响应/错误日志?
  • @jbrahy 试过了,我得到了 - 语法错误,JSON 格式错误。
  • 转到jsonlint.com并检查JSON是否有效并修改它直到它有效。那么这应该可以正常工作。

标签: php json curl


【解决方案1】:

更新了 curl 选项并设置了 ini user_agent。经过测试并且可以工作。

<?php
ini_set('user_agent','MSIE 4\.0b2;'); // this is required. otherwise you'll get a 401

// Setup cURL
$url = "http://api.mirai.so/external/test";
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_SSL_VERIFYPEER => FALSE,
    CURLOPT_RETURNTRANSFER => TRUE,
));
$response = curl_exec($ch); // Send the request

// Check for errors
IF ($response === FALSE) {
    echo "Error!";
}ELSE{
  $result = json_decode($response, true);
  die("<pre>".print_r($result, true)."</pre>"); // prettier
}
?>

【讨论】:

  • echo() 不解码响应并查看格式。如果不是太大,请在原始帖子中发布。您的 JSON 格式不正确。
  • 我现在收到 400 错误请求 cloudflare-nginx!
  • 试试DIE($response);
  • 在它下面我也得到了 - 语法错误,格式错误的 JSON
  • 我再次收到 400 Bad Request cloudflare-nginx 但这次没有 - 语法错误,JSON 格式错误
【解决方案2】:

您将var_dump 函数(返回null)的结果分配给$result 变量。 你为什么这样做?

您应该将json_decode 结果分配给$result

$result = json_decode($response, TRUE);

【讨论】:

  • 我在运行 json_last_error() 后得到了 - 语法错误,JSON 格式错误
  • 那么 - var_dump($response),它是什么?
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 2012-09-13
相关资源
最近更新 更多