【发布时间】:2011-05-24 22:52:38
【问题描述】:
我到处研究过,但无法弄清楚。
我正在编写一个测试 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 addlashes() 在引号前添加斜杠
没有任何作用。
任何想法为什么 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;
}
【问题讨论】:
-
这可能不是问题(因此是评论而不是答案),但您需要在使用 cURL 发送之前
urlencode()JSON 字符串。 php.net/urlencode -
我在将 JSON 字符串发送到 cURL 之前对其进行了编码,但结果仍然相同。这快把我逼疯了!不过感谢您的建议。
-
在
if (isset($data['data'])) {之后,您可以添加var_dump($data['data']);并发布它显示的内容吗? -
它打印出: string(99) "{"products":{"product1":"abc","product2":"pass"}}" 然后我为 JSON 做了同样的 var_dump发送并打印出来: string(49) "{"products":{"product1":"abc","product2":"pass"}}" 如果我在 urlencode() 版本上做同样的事情它打印出的 JSON 对象: string(85) "%7B%22products%22%3A%7B%22product1%22%3A%22abc%22%2C%22product2%22%3A%22pass%22%7D%7D"
-
我也试过 preg_replace("[^A-Za-z0-9]", "", $data);在 string(99) 的字符串上,没有任何改变。