Heim  >  Artikel  >  Backend-Entwicklung  >  如何用PHP获取无字段的json数据

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

WBOY
WBOYOriginal
2016-06-20 13:02:261154Durchsuche

如何用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是一模一样的。


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php验证类代码Nächster Artikel:新手学习PHP建站步骤总结