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

How Do I Parse Result From curl_exec to extract json data in PHP

我收到了执行 curl_exec 的结果,其中包含 json 数据和其他数据。我不知道如何编辑这个结果。特别是,我需要从结果中包含的 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"}

如何更改 "error" 的值?仅使用 json_decode 本身似乎并不是一种有效的方法。它 returns 一个 NULL 结果:

$obj = json_decode($response);

建议?

你试过了吗:

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 忽略 headers,你应该只会得到 {"error":"invalid_grant"}

现在,综上所述,header 用两个换行符将 body 分开。所以你也应该能够这样解析它:

$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);