阅读json输入php [英] Reading json input in php
问题描述
php:// input
在localhost中正常工作。但在服务器中它返回空。
到我的网站的输入(请求)是 json
( REST-应用程序/ json类型),因此 $ _POST
无法使用(请参阅这个问题 )。
$ _ POST与键值对类型输入类似,如form-data或x-www-urlencoded
key1 = value1& key2 = value2& key3 = value3
我使用 application / json
作为输入(在 REST 中)。
Like {'key1':'value1','key2':'value2','key3':'value3'}
这不能使用 $ _ POST
来处理。但是使用 php:// input
可以帮助读取这些数据。
我的代码
class Webservice_Controller extends CI_Controller {
public $ json_input_data;
public function __construct(){
parent :: __ construct();
$ this-> json_input_data = json_decode(file_get_contents('php:// input'),TRUE);
}
public function json_input($ label){
if(isset($ this-> json_input_data [$ label]))return $ this-> json_input_data [$ label];
else return NULL;
}
}
以上代码在另一个网络服务器中正常工作也,但不是在目前的一个。 :
我认为我的网络服务器拒绝访问 php:// input
p>
我知道这是老的,但它可能会帮助别人:
小心使用json中的单引号
从关于json_decode的PHP文档:
名称和值必须用双引号括起
单引号无效
$ bad_json ={'bar':'baz'} ;
json_decode($ bad_json); // null
php://input
is working properly in localhost. But in server it returns empty.
Input( request ) to my site is a json
(REST - application/json type), so $_POST
didn't work ( please read This question ) .
$_POST works with key-value pair type inputs like form-data or x-www-urlencoded
key1=value1&key2=value2&key3=value3
I'm using application/json
as input (in REST).
Like {'key1':'value1','key2':'value2','key3':'value3'}
This can't be handled using $_POST
. But using php://input
can help to read that data.
My code
class Webservice_Controller extends CI_Controller {
public $json_input_data;
public function __construct(){
parent::__construct();
$this->json_input_data = json_decode(file_get_contents('php://input'),TRUE);
}
public function json_input($label){
if(isset($this->json_input_data[$label])) return $this->json_input_data[$label];
else return NULL;
}
}
Above code is works fine in another webserver also, But not in the current one. :(
I think my web server deny access to php://input
.
Is there is any other methods to read json input in php ?
I know this is old, but it might help others:
Careful with single quotes inside your json
From the PHP documentation about json_decode:
the name and value must be enclosed in double quotes
single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
这篇关于阅读json输入php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!