为了账号安全,请及时绑定邮箱和手机立即绑定

使用PHP读取JSON帖子

使用PHP读取JSON帖子

PHP
慕森王 2019-06-16 15:03:08
使用PHP读取JSON帖子在发布这个问题之前,我看了很多遍,所以我很抱歉,如果它在另一个帖子上,这只是我在这里的第二个问题,所以如果我没有正确地设置这个问题的格式,那么很抱歉。我已经创建了一个非常简单的Web服务,需要获取POST值并返回一个JSON编码数组。这一切都很好,直到我被告知我需要用一个内容类型的应用程序/json发布表单数据。从那时起,我不能从Web服务返回任何值,这肯定与我如何过滤他们的POST值有关。基本上,在我的本地设置中,我创建了一个测试页面,它执行以下操作-$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);在webservice上我有这个(我已经删除了一些功能)-<?phpheader('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);?>基本上,我知道这是由于没有设置$_post值,但是我找不到我需要放的东西,而不是$_post。我尝试了json_decode($_post)、file_get_content(“php:/input”)和许多其他方式,但是我在黑暗中拍摄了一些东西。任何帮助都将不胜感激。
查看完整描述

3 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

您可以将json放入参数并发送它,而不是只将json放在头文件中:

$post_string= 'json_param=' . json_encode($data);//open connection$ch = curl_init();//set the url, number of POST vars, POST datacu
rl_setopt($ch,CURLOPT_POST, 1);curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);curl_setopt($curl, CURLOPT_URL, ' 
.local/');  // Set the url path we want to call//execute post$result = curl_exec($curl);//see the results$json=json_decode($result,tr
ue);curl_close($curl);print_r($json);

在服务端,您可以将json字符串作为参数:

$json_string = $_POST['json_param'];$obj = json_decode($json_string);

然后,您可以使用转换后的数据作为对象。



查看完整回答
反对 回复 2019-06-16
  • 3 回答
  • 0 关注
  • 535 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信