0

I have received a result from the execution of curl_exec that contains json data and other data. I cannot figure out how to edit this result. In particular, I need to edit a value from the json data contained in the result. For example, given the following result:

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"}

how can I change the value of "error"? Just using json_decode doesn't seem to be a valid method by itself. It returns a NULL result with:

$obj = json_decode($response);

Suggestions?

1 Answer 1

3

Have you tried:

curl_setopt($s,CURLOPT_HEADER,false); 

Basically, what you are receiving is a complete response from a server:

# 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"}

By telling cURL to ignore the headers, you should only get {"error":"invalid_grant"}

Now, all of that said, the header separates the body by two newlines. So you should also be able to parse it that way:

$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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.