如何从curl_exec解析结果以在PHP中提取json数据

时间:2015-01-10 17:41:57

标签: php json curl

我收到了执行包含json数据和其他数据的curl_exec的结果。我无法弄清楚如何编辑这个结果。特别是,我需要编辑结果中包含的json数据中的值。例如,给出以下结果:

RESPONSE: HTTP/1.1 400 Bad Request
Server: nginx
Date: Sat, 10 Jan 2015 17:31:02 GMT
Content-Type: application/json
Content-Length: 25
Connection: keep-alive
Keep-Alive: timeout=10

{"error":"invalid_grant"}

如何更改“错误”的值?仅使用json_decode本身似乎不是一个有效的方法。它返回NULL结果:

$obj = json_decode($response);

建议?

1 个答案:

答案 0 :(得分:3)

你试过了吗?

curl_setopt($s,CURLOPT_HEADER,false); 

基本上,您收到的是来自服务器的完整回复:

# these are the headers
RESPONSE: HTTP/1.1 400 Bad Request
Server: nginx
Date: Sat, 10 Jan 2015 17:31:02 GMT
Content-Type: application/json
Content-Length: 25
Connection: keep-alive
Keep-Alive: timeout=10

# This is the body.
{"error":"invalid_grant"}

告诉cURL忽略标题,您应该只获得{"error":"invalid_grant"}

现在,所有这些都说,标题将正文分隔两个换行符。所以你也应该能够这样解析它:

$val = curl_exec();

// list($header,$body) = explode("\n\n", $val); won't work: \n\n is a valid value for 
// body, so we only care about the first instance.
$header = substr($val, 0, strpos($val, "\n\n"));
$body = substr($val, strpos($val, "\n\n") + 2);
// You *could* use list($header,$body) = preg_split("#\n\n#", $val, 2); because that
// will create an array of two elements.

// To get the value of *error*, you then
$msg = json_decode($body);
$error = $msg->error;

/*
 The following are because you asked how to "change the value of `error`".
 You can safely ignore if you don't want to put it back together.
*/
// To set the value of the error:
$msg->error = 'Too many cats!';

// to put everything back together:
$replaced = $header . "\n\n" . json_encode($msg);