2017-07-02 174 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