在 PHP 中處理 application/json
數(shù)據(jù),您需要首先獲取 JSON 數(shù)據(jù)并將其解碼為 PHP 對象或關聯(lián)數(shù)組
獲取 JSON 數(shù)據(jù):
通常,JSON 數(shù)據(jù)是通過 HTTP POST 請求的主體發(fā)送的。您可以使用 file_get_contents()
函數(shù)從輸入流中讀取原始 POST 數(shù)據(jù)。
$json_data = file_get_contents('php://input');
解碼 JSON 數(shù)據(jù):
使用 json_decode()
函數(shù)將 JSON 字符串轉(zhuǎn)換為 PHP 對象或關聯(lián)數(shù)組。
// 將 JSON 數(shù)據(jù)解碼為 PHP 對象
$data_object = json_decode($json_data);
// 將 JSON 數(shù)據(jù)解碼為關聯(lián)數(shù)組
$data_array = json_decode($json_data, true);
處理解碼后的數(shù)據(jù):
現(xiàn)在您可以像處理普通 PHP 對象或關聯(lián)數(shù)組一樣處理解碼后的數(shù)據(jù)。
示例:
if (json_last_error() === JSON_ERROR_NONE) {
if (is_object($data_object)) {
echo "Name: " . $data_object->name . "\n";
echo "Email: " . $data_object->email . "\n";
} elseif (is_array($data_array)) {
echo "Name: " . $data_array['name'] . "\n";
echo "Email: " . $data_array['email'] . "\n";
}
} else {
echo "Invalid JSON data.";
}
完整示例:
<?php
$json_data = file_get_contents('php://input');
$data_object = json_decode($json_data);
$data_array = json_decode($json_data, true);
if (json_last_error() === JSON_ERROR_NONE) {
if (is_object($data_object)) {
echo "Name: " . $data_object->name . "\n";
echo "Email: " . $data_object->email . "\n";
} elseif (is_array($data_array)) {
echo "Name: " . $data_array['name'] . "\n";
echo "Email: " . $data_array['email'] . "\n";
}
} else {
echo "Invalid JSON data.";
}
?>
這個示例展示了如何在 PHP 中處理 application/json
數(shù)據(jù)。首先,從輸入流中讀取 JSON 數(shù)據(jù),然后將其解碼為 PHP 對象或關聯(lián)數(shù)組。最后,根據(jù)解碼后的數(shù)據(jù)類型(對象或數(shù)組)處理數(shù)據(jù)。