使用 PHP 读取 JSON POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19004783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading JSON POST using PHP
提问by Steve Matthews
I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don't format this question correctly.
在发布这个问题之前,我环顾了很多,所以如果它在另一个帖子上,我很抱歉,这只是我在这里的第二个问题,所以如果我没有正确格式化这个问题,我很抱歉。
I have a really simple web service that I have created that needs to take post values and return a JSON encoded array. That all worked fine until I was told I would need to post the form data with a content-type of application/json. Since then I cannot return any values from the web service and it is definitely something to do with how I am filtering their post values.
我创建了一个非常简单的 Web 服务,它需要获取 post 值并返回一个 JSON 编码的数组。一切都很好,直到我被告知我需要发布内容类型为 application/json 的表单数据。从那时起,我无法从 Web 服务返回任何值,这绝对与我如何过滤它们的 post 值有关。
Basically in my local setup I have created a test page that does the following -
基本上在我的本地设置中,我创建了一个执行以下操作的测试页面 -
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
On the webservice I have this (I have stripped out some of the functions) -
在网络服务上我有这个(我已经去掉了一些功能)-
<?php
header('Content-type: application/json');
/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');
if(isset($_POST['action']) && $_POST['action'] == 'login') {
$statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
$posts[] = array('status'=>$statusCode);
header('Content-type: application/json');
echo json_encode($posts);
/* disconnect from the db */
}
@mysql_close($link);
?>
Basically I know that it is due to the $_POST values not being set but I can't find what I need to put instead of the $_POST. I tried json_decode($_POST), file_get_contents("php://input") and a number of other ways but I was shooting in the dark a bit.
基本上我知道这是由于未设置 $_POST 值,但我找不到我需要放置的内容而不是 $_POST。我尝试了 json_decode($_POST)、file_get_contents("php://input") 和许多其他方法,但我有点在黑暗中拍摄。
Any help would be greatly appreciated.
任何帮助将不胜感激。
Thanks, Steve
谢谢,史蒂夫
Thanks Michael for the help, that was a definite step forward I now have at least got a repsonse when I echo the post....even if it is null
感谢迈克尔的帮助,这是向前迈出的明确一步,我现在至少在我回应帖子时得到了回应......即使它是空的
updated CURL -
更新的卷曲 -
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
updated php on the page that the data is posted to -
在数据发布到的页面上更新了 php -
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r(json_encode($input));
As I say at least I see a response now wheras prior it was returning a blank page
正如我所说的,至少我现在看到了一个响应,而之前它返回的是一个空白页
回答by Michael Sivolobov
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
你有空$_POST
。如果您的网络服务器想要查看 json 格式的数据,您需要读取原始输入,然后使用 JSON 解码对其进行解析。
You need something like that:
你需要这样的东西:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
你也有错误的代码来测试 JSON 通信......
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
CURLOPT_POSTFIELDS
告诉curl
将您的参数编码为application/x-www-form-urlencoded
. 此处需要 JSON 字符串。
UPDATE
更新
Your php code for test page should be like that:
你的测试页面的 php 代码应该是这样的:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
同样在您的网络服务页面上,您应该删除其中一行header('Content-type: application/json');
。它只能被调用一次。
回答by syd619
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
你好,这是我的一个旧项目的片段,它使用 curl 从一些以 json 格式回复的免费 ip 数据库服务获取 ip 信息。我想它可能对你有帮助。
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
功能:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
回答by morteza kavakebi
you can put your json in a parameter and send it instead of put only your json in header:
您可以将您的 json 放在一个参数中并发送它,而不是只将您的 json 放在标题中:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
在服务端,您可以将 json 字符串作为参数:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.
然后您可以将转换后的数据用作对象。