如何解析PHP中CURL返回的JSON值?

时间:2017-07-02 17:54:06

标签: php json wordpress curl

我能够通过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时。我的目标是为我存储错误消息变量它是{"消息":"电子邮件已被使用"}

的消息值

任何提示?

非常感谢!

1 个答案:

答案 0 :(得分:3)

handleLogin

cURL请求是否返回了标头 您必须将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 设置为CURLOPT_HEADERFALSE)才能从输出中删除标题:

0

curl_setopt($curl, CURLOPT_HEADER, 0); CURLOPT_HEADER所述,TRUE $(".sessionSignOutBtn").submit(function(event) { event.preventDefault(); newAjaxRequest($(this).serialize(), "index.php?ajax=sessionSignOut", removedSessionBox); $(this).parent().parent().fadeOut("slow", function() { $(this).remove(); }); if($("#otherSessions").is(':empty')) { $("#otherSessionsTitle").text("No other active sessions"); } }); 标题将包含在输出中。