猿问

使用PHP读取JSON帖子

使用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上我有这个(我已经删除了一些功能)-


<?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);?>

基本上,我知道这是由于没有设置$_post值,但是我找不到我需要放的东西,而不是$_post。我尝试了json_decode($_post)、file_get_content(“php:/input”)和许多其他方式,但是我在黑暗中拍摄了一些东西。


任何帮助都将不胜感激。



慕森王
浏览 536回答 3
3回答

撒科打诨

您可以将json放入参数并发送它,而不是只将json放在头文件中:$post_string=&nbsp;'json_param='&nbsp;.&nbsp;json_encode($data);//open&nbsp;connection$ch&nbsp;=&nbsp;curl_init();//set&nbsp;the&nbsp;url,&nbsp;number&nbsp;of&nbsp;POST&nbsp;vars,&nbsp;POST&nbsp;datacu rl_setopt($ch,CURLOPT_POST,&nbsp;1);curl_setopt($ch,CURLOPT_POSTFIELDS,&nbsp;$post_string);curl_setopt($curl,&nbsp;CURLOPT_URL,&nbsp;'&nbsp; .local/');&nbsp;&nbsp;//&nbsp;Set&nbsp;the&nbsp;url&nbsp;path&nbsp;we&nbsp;want&nbsp;to&nbsp;call//execute&nbsp;post$result&nbsp;=&nbsp;curl_exec($curl);//see&nbsp;the&nbsp;results$json=json_decode($result,tr ue);curl_close($curl);print_r($json);在服务端,您可以将json字符串作为参数:$json_string&nbsp;=&nbsp;$_POST['json_param'];$obj&nbsp;=&nbsp;json_decode($json_string);然后,您可以使用转换后的数据作为对象。
随时随地看视频慕课网APP
我要回答