2017-07-02 38 views
0

我能夠成功地通過CURL發送POST值,但我似乎無法弄清楚如何獲取它返回的唯一JSON代碼。如何解析PHP中CURL返回的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 
    ); 
} 

我能夠得到的$響應變量,但返回的消息正確的值給我:

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。我打算爲我存儲錯誤消息變量它是在{「消息」中的消息的值:「電子郵件已在使用中」}

任何提示?

非常感謝!

+0

你試過在cURL執行後json編碼嗎? –

+0

「400錯誤請求」向我建議,由於客戶端錯誤,服務器沒有處理您的請求。端點是否明確接受POST請求? $ data變量是否包含所有必需的字段? – Freid001

回答

3
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_HEADERFALSE0)從輸出中刪除標題:

curl_setopt($curl, CURLOPT_HEADER, 0); 

正如documentation陳述時CURLOPT_HEADERTRUE頭將被包含在輸出中。

+0

Ahhhh這是我錯過的一個小細節。非常感謝! – Atasha