2015-01-10 23 views
0

我收到了包含json數據和其他數據的執行curl_exec的結果。我無法弄清楚如何編輯這個結果。特別是,我需要從結果中包含的json數據編輯一個值。例如,給出以下結果:如何從curl_exec解析結果以提取PHP中的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); 

建議?

回答

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

通過告訴捲曲忽略標題,你應該只得到{"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);