使用PHP读取JSON POST

使用PHP读取JSON POST,php,json,post,Php,Json,Post,在发布这个问题之前,我环顾了很多地方,所以如果它出现在另一篇文章中,我表示歉意,这只是我在这里的第二个问题,如果我没有正确设置这个问题的格式,我表示歉意 我创建了一个非常简单的web服务,它需要获取post值并返回一个JSON编码的数组。在我被告知需要使用application/json的内容类型发布表单数据之前,一切都很顺利。从那时起,我无法从web服务返回任何值,这肯定与我如何过滤他们的帖子值有关 基本上,在我的本地设置中,我创建了一个测试页面,它执行以下操作- $curl = curl_i

在发布这个问题之前,我环顾了很多地方,所以如果它出现在另一篇文章中,我表示歉意,这只是我在这里的第二个问题,如果我没有正确设置这个问题的格式,我表示歉意

我创建了一个非常简单的web服务,它需要获取post值并返回一个JSON编码的数组。在我被告知需要使用application/json的内容类型发布表单数据之前,一切都很顺利。从那时起,我无法从web服务返回任何值,这肯定与我如何过滤他们的帖子值有关

基本上,在我的本地设置中,我创建了一个测试页面,它执行以下操作-

$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-

$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array

print_r(json_encode($input));

正如我所说,至少我现在看到了一个响应,而之前它返回的是一个空白页

您好,这是我的一个老项目的一个片段,它使用curl从一些免费的ip数据库服务获取ip信息,这些服务以json格式回复。我想这可能对你有帮助

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);
功能:

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

            } 

        }
    }
函数getUserLocation($services){
$ctx=stream\u context\u create(数组('http'=>array('timeout'=>15));//15秒超时
对于($i=0;$itrue,//返回网页
//CURLOPT_HEADER=>false,//不返回头
CURLOPT_HTTPHEADER=>array('Content-type:application/json'),
CURLOPT_FOLLOWLOCATION=>true,//跟随重定向
CURLOPT_ENCODING=>“”,//句柄已压缩
CURLOPT_USERAGENT=>“test”//我是谁
CURLOPT_AUTOREFERER=>true,//在重定向时设置referer
CURLOPT_CONNECTTIMEOUT=>5,//连接超时
CURLOPT_TIMEOUT=>5,//响应超时
CURLOPT_MAXREDIRS=>10//在10次重定向后停止
); 
//初始化卷曲
$ch=curl_init($services[$i]);
curl_setopt_数组($ch$options);
$content=curl\u exec($ch);
$err=curl\u errno($ch);
$errmsg=curl\u error($ch);
$header=curl\u getinfo($ch);
$httpCode=curl\u getinfo($ch,CURLINFO\u HTTP\u代码);
卷曲关闭($ch);
//回显“服务:”.$services[$i]”。
; //回音“err:”.$err.
”; //回显“errmsg:”.$errmsg.
”; //回显“httpCode:”.$httpCode.
”; //打印(页眉); //打印(json解码($content,true)); 如果($err==0&&$httpCode==200&&$header['download\u content\u length']>0){ 返回json_decode($content,true); } } }
您有空的
$\u POST
。如果web服务器希望查看json格式的数据,则需要读取原始输入,然后使用json解码对其进行解析

你需要这样的东西:

$json = file_get_contents('php://input');
$obj = json_decode($json);
$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);
另外,您在测试JSON通信时使用了错误的代码

CURLOPT\u POSTFIELDS
告诉
curl
将参数编码为
application/x-www-form-urlencoded
。这里需要JSON字符串

更新

测试页面的php代码应该如下所示:

$json = file_get_contents('php://input');
$obj = json_decode($json);
$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);

另外,在web服务页面上,您应该删除一行
标题('Content-type:application/json')。只能调用一次。

您可以将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);
在服务端,您可以获取json字符串作为参数:

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

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

不确定失败的原因是什么,但我想,第一步是打印出$\u POST的内容,查看其中的内容。如果有数据,处理它们就很容易了。如果$\u POST是空的,至少你知道问题出在哪里。谢谢你的代码片段,但我认为我的问题出在webservice/PHP方面,而不是CURL代码(尽管你可以随意告诉我,因为我不是100%)。我认为这是我的PHP$\u POST值,以及它们是否需要json编码或其他东西。嗯,尝试将其添加到您的curl curl\u setopt($curl,CURLOPT\u UPLOAD,1);谢谢Michael,这帮了大忙,你能看一下我的编辑,看看还有没有其他引起我问题的原因吗?伙计,这太有帮助了!代码$json=file\u get\u contents('php://input'); $obj=json_decode($json);工作完美我害怕花一整天的时间来完成这项任务。。。但是很酷,它在不到2分钟的时间内就成功了!非常感谢你,现在我可以假装这很难,然后请一天假……对我来说,帮助$json=file\u获取内容('php://input'); $obj=json_decode($json,true);否则我会出现错误“无法将stdClass类型的对象用作数组”。我将$data作为json发送给对象。