使用 PHP 读取 JSON POST


Reading JSON POST using PHP

在发布这个问题之前,我环顾四周,所以如果它是在另一个帖子上,我深表歉意,这只是我在这里的第二个问题,所以如果我没有正确格式化这个问题,请道歉。

我创建了一个非常简单的 Web 服务,需要获取 post 值并返回 JSON 编码数组。这一切都工作正常,直到我被告知我需要使用应用程序/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);

在网络服务上,我有这个(我已经删除了一些功能(-

<?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_contents("php://input"(和其他一些方式,但我在黑暗中拍摄了一点。

任何帮助将不胜感激。

谢谢,史蒂夫

感谢迈克尔的帮助,这是向前迈出的明确一步,我现在至少在回复帖子时得到了回复......即使它为空

更新的卷曲 -

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

在数据发布到的页面上更新了 PHP -

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

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

你有空的$_POST。如果您的 Web 服务器想要查看 json 格式的数据,您需要读取原始输入,然后使用 JSON 解码对其进行解析。

你需要这样的东西:

$json = file_get_contents('php://input');
$obj = json_decode($json);

此外,您有错误的代码来测试JSON通信...

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

更新

测试页的 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);

同样在您的 Web 服务页面上,您应该删除其中一行header('Content-type: application/json');。它只能调用一次。

您好,这是我的一个旧项目的一个片段,该项目使用 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 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);
            } 
        }
    }

您可以将 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);

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