PHP POST JSON 参数传递与接收处理
首先介绍第一个页面,即负责发送 JSON 数据的 PHP 页面逻辑。
该文件命名为 1.php,用于构造并发送请求。
<?
function http_post_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
//echo $return_content."
";
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// return array($return_code, $return_content);
return $return_content;
}
$url = "http://127.0.0.1/2.php";
$data = json_encode(array('a'=>"weqweqwe", 'b'=>2));
//list($return_code, $return_content) = http_post_data($url, $data);
$aaa = http_post_data($url, $data);
//print_r($aaa);
echo $aaa;
$ccc=json_decode($aaa);
print_r($ccc);
echo $ccc->b;
echo "";
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?>
接着是第二个页面,主要负责接收和处理传入的参数。
该文件命名为 2.php,执行具体的解析操作。
<?
$postData = file_get_contents('php://input');
echo $postData;
$data = json_encode(array('a'=>" 234 ", 'b'=>2));
echo $data;
?>
上述内容即为 PHP 中 POST 传递 JSON 参数的完整处理方法,希望能为开发者提供参考,欢迎继续支持本站获取更多技术分享。