【问题标题】:How to parse ONLY the JSON value returned by CURL in PHP?如何仅解析 PHP 中 CURL 返回的 JSON 值?
【发布时间】:2017-07-02 17:54:05
【问题描述】:

我能够通过 CURL 成功发送 POST 值,但我似乎无法弄清楚如何获取它返回的唯一 JSON 代码。

这是我的代码的一部分:

try {
    $curl = curl_init($url);

    if (FALSE === $curl)
        throw new Exception('failed to initialize');

    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json")
    );          
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");   
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

    $message = curl_exec($curl);

    if (FALSE === $message)
        throw new Exception(curl_error($curl), curl_errno($curl));

    $response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = $message;

    var_dump($error);
    curl_close($curl);

} catch(Exception $e) {
    trigger_error(
        sprintf(
            'Curl failed with error #%d: %s',
            $e->getCode(), $e->getMessage()
        ),
        E_USER_ERROR
    );
}

我能够得到 $response 变量的正确值,但返回的消息给了我:

string(253) "HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38 {"Message":"Email is already in used"}"

当我尝试使用 var_dump 时。我的目标是为我存储错误消息变量,它是 {"Message":"Email is already in used"}

中的 Message 值

有什么建议吗?

非常感谢!

【问题讨论】:

  • 你有没有试过在 cURL 执行后进行 json 编码?
  • "400 Bad Request" 向我建议,由于客户端错误,服务器未处理您的请求。端点是否肯定接受 POST 请求? $data 变量是否包含所有必填字段?

标签: php json wordpress curl


【解决方案1】:
HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38

是 cURL 请求返​​回的标头。
您必须将 CURLOPT_HEADER 设置为 FALSE (0) 才能从输出中删除标题:

curl_setopt($curl, CURLOPT_HEADER, 0);

documentation 所述,当CURLOPT_HEADERTRUE 时,标头将包含在输出中。

【讨论】:

  • 啊啊啊这是我错过的一个小细节。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-10-25
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
  • 2014-02-05
  • 1970-01-01
相关资源
最近更新 更多