我到处研究过,但无法弄清楚这一点。
我正在编写一个测试 cUrl 请求来测试我的 REST 服务:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
这工作正常,请求被我的服务接受,并且 $_Post 根据需要填充,包含两个变量:订单和数据。数据具有编码的 JSON 对象。当我打印 $_Post['data'] 时,它显示:
{"products":{"product1":"abc","product2":"pass"}}
这正是预期的并且与发送的内容相同。
当我尝试解码时,json_decode() 什么也没有返回!
如果我创建一个新字符串并手动输入该字符串,则 json_decode() 工作正常!
我试过了:
strip_tags() 删除可能已添加到 http 帖子中的任何标签
utf8_encode() 将字符串编码为所需的utf 8
addslashes() 在引号前添加斜杠
什么都不起作用。
有什么想法为什么 json_decode() 在从 http post 消息收到字符串后不起作用?
以下是我处理请求的相关部分,供参考:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}