本文目錄一覽:
php如何發送和接收JSON數據
對於json,PHP有對應的方法進行操作。
一般而言,json會以字符串形式傳給PHP腳本,一般都是放在$_POST裏面,
14
?php
// 接收
$json_parameter = $_POST[‘json_str’];
// 處理, 變成數組
$array = json_decode($json_parameter);
// PHP 把數組數據變成json格式字符串,發給頁面
$demo = array(
‘key’ = ‘value’,
‘key2’ = ‘value2’
);
$demo_json = json_encode($demo); // 格式是{“key”:”value”,”key2″:”value2″}
echo $demo_json;
php 接收 json 數據,並解釋
加入對方是post過來的。name 為orderInfo;
?php
$orderInfo = isset($_post[‘orderInfo’]) ? trim($_post[‘orderInfo’]) : ”;
if(strlen($orderInfo) 1) {
die(‘wrong data’);
}
//希望你能寫一個更嚴格的驗證函數,去驗證數據的合法性
$orderInfoArray = json_decode($orderInfo, true);
if(!$orderInfoArray) {
die(‘錯誤的數據格式’)
}
/*
*然後數據的格式就轉化為
*array(
* ‘topic’ =’trade’,
* ‘status’ =’TradeCreate’,
* ………
* )
*
*
*/
?
PHP json數據寫入到json文件,讀取json文件
// 生成一個PHP數組
$data = array();
$data[‘name’] = ‘admin’;
$data[‘pwd’] = ‘123456’;
// 把PHP數組轉成JSON字符串
$json_string = json_encode($data);
// 寫入文件
file_put_contents(‘user.json’, $json_string);
// 從文件中讀取數據到PHP變量
$json_string = file_get_contents(‘user.json’);
// 把JSON字符串轉成PHP數組
$data = json_decode($json_string, true);
// 顯示出來看看
var_dump($data)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/157021.html