在php中读取json输入 [英] Reading json input in php
问题描述
php://input
在本地主机中正常工作.但是在服务器中它返回空.我网站的输入(请求)是 json
(REST - 应用程序/json 类型),所以 $_POST
不起作用(请阅读这个问题 ) .
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 适用于键值对类型输入,例如 form-data 或 x-www-urlencoded
$_POST works with key-value pair type inputs like form-data or x-www-urlencoded
key1=value1&key2=value2&key3=value3
我使用 application/json
作为输入(在 REST 中).
I'm using application/json
as input (in REST).
喜欢 {'key1':'value1','key2':'value2','key3':'value3'}
Like {'key1':'value1','key2':'value2','key3':'value3'}
这无法使用 $_POST
处理.但是使用 php://input
可以帮助读取该数据.
This can't be handled using $_POST
. But using php://input
can help to read that data.
我的代码
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;
}
}
上面的代码在另一个网络服务器中也可以正常工作,但在当前的网络服务器中却没有.:(
我认为我的 Web 服务器拒绝访问 php://input
.
I think my web server deny access to php://input
.
还有其他方法可以读取 php 中的 json 输入吗?
推荐答案
我知道这是旧的,但它可能会帮助其他人:
I know this is old, but it might help others:
注意 json 中的单引号
来自关于 json_decode 的 PHP 文档:
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
这篇关于在php中读取json输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!