首页  >  文章  >  后端开发  >  如何用PHP获取无字段的json数据

如何用PHP获取无字段的json数据

WBOY
WBOY原创
2016-06-20 13:02:261066浏览

如何用PHP获取无字段的json数据

1、如何用PHP获取json数据?

解决这个问题,通常的解决方式是这样的:
$jsonData = $_POST[‘jsonstr’];
此方式需要客户端提交一个jsonstr的参数过来,里面含的数据是json字符串,然后在服务端解析。

2、客户端直接传json数据过来

如果客户端直接传json数据过来,而没有上述jsonstr的参数。使用$_GET,$_POST 和 $_REQUEST是获取不到数据的。
解决的办法就是使用使用$GLOBALS这个全局变量,$GLOBALS[‘HTTP_RAW_POST_DATA’]就能获取客户端传来的json数据了。

下面给出Thinkphp中控制器的使用curl提交数据代码:

class CcAction extends Action {
 public function getjson(){
 echo json_encode($GLOBALS['HTTP_RAW_POST_DATA']);//这里就能获取到testcurl传来的$json_string
 }
 public function testcurl(){
 $header = array('Accept:application/json', 'Content-Type:application/json');
 $patoken = array(
 'name' => 'phpjyz',
 'age' => '23',
 );
 $json_string = json_encode($patoken);
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
 curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
 
 curl_setopt($ch, CURLOPT_URL, 'http://www.scutephp.com/api.php/cc/getjson');
 curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 $ret = curl_exec($ch);
 print_r(json_decode($ret, true));
 }
}

返回的数据和$json_string是一模一样的。


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn