【问题标题】:php curl rest api response not in json formatphp curl rest api响应不是json格式
【发布时间】:2019-01-04 11:23:22
【问题描述】:

我在做一个 post curl 请求

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_POST, 1);
        $headers = array();
        $headers = ["Content-Type:application/json","Accept:application/json"];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close ($ch);
        return $result;

上面的 curl 请求应该返回一个 json 格式的字符串,但是得到一个 javascript 对象形式的字符串。

string(68) "{data:{errorCode:AC01,errorMessage:SansID 53563857 is exist.}}"

当我尝试从 post man api 做同样的事情时返回完美的 json。

{"data":{"errorCode":"AC01","errorMessage":"SansID 53563857 is exist."}}

请让我知道我哪里做错了。

【问题讨论】:

  • 无论你得到什么响应都不是 curl_* 函数的错。如果不了解更多信息,任何人都无法就该 API 提出建议。
  • 您是否使用 var_dump() 打印响应数据?
  • 我认为 API 响应没问题,请使用 json_decode() 方法将 json 转换为数组并使用 print_r 方法打印该值。
  • @sohanverma 我使用了 dd(),当 json_decode() 给出的字符串为 NULL
  • 好的,请在 $result = curl_exec($ch); 之后使用 json_decode线。请使用此代码:$responseArray = json_decode($result); print_r($responseArray);死;请检查我的建议,如果仍然有同样的错误,请告诉我。

标签: php json curl php-curl


【解决方案1】:

使用 json_decode 将 String 转换为 Object (stdClass) 或数组: 我在使用 WordPress(cURL) 和 Laravel(passport) 支持的 API 时遇到了同样的问题,这些 API 返回 JSON 但以字符串格式。我保存了回复

//save json string into variable json object and return result
$response = curl_exec($curl);
//convert t
return (json_decode($response));

请参阅此链接here 以获得类似的解决方案

看看这个截图console logs for before and after the fix

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2022-01-15
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多