dongxie8906 2018-07-27 10:37
浏览 293

php curl rest api响应不是json格式

I doing a post curl request

        $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;

The above curl request should return a json formated string but getting a string in javascript object form.

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

Where as when i try to do the same thing from post man api is returning perfect json.

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

Please let me know where i'm doing wrong.

  • 写回答

1条回答 默认 最新

  • douqiangchuai7674 2019-08-29 08:07
    关注

    Use json_decode to convert String into Object (stdClass) or array: I was having the same issue working with WordPress(cURL) and Laravel(passport) powered API that was returning JSON but in string format. I saved the response

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

    refer to this link here for a similar solution

    Check out this screenshot console logs for before and after the fix

    评论

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题