如何在 PHP 中解析 JSON 檔案 及POST接收檔案
示例程式碼中使用的 JSON 檔案的內容如下。[
{
"id": "01",
"name": "Olivia Mason",
"designation": "System Architect"
},
{
"id": "02",
"name": "Jennifer Laurence",
"designation": "Senior Programmer"
},
{
"id": "03",
"name": "Medona Oliver",
"designation": "Office Manager"
}
]如果要處理 JSON POST 請求:
// 從請求中獲取原始數據
$json = file_get_contents('php://input');
// 將其轉換為 PHP 對象
$data = json_decode($json);
使用 file_get_contents() 函式解析 PHP 中的 JSON 檔案
內建函式 file_get_contents() 用於讀取檔案並將其儲存為字串。通過使用此函式,我們可以將 JSON 檔案解析為字串。使用此函式的正確語法如下。
file_get_contents($pathOfFile, $searchPath, $customContext, $startingPoint, $length);
此函式接受五個引數。這些引數的詳細資訊如下。
引數
描述
pathOfFile強制性的它指定檔案的路徑
searchPath可選的它指定搜尋檔案的路徑
customContext可選的它用於指定自定義上下文
startingPoint可選的它指定讀取檔案的起點
length可選的它是要讀取的檔案的最大長度(以位元組為單位)
以下程式顯示瞭如何解析 JSON 檔案。
<?php
$JsonParser = file_get_contents("myfile.json");
var_dump($JsonParser);
?>
函式 file_get_contents() 僅解析儲存在 JSON 檔案中的 JSON 資料。我們無法直接使用此資料。
輸出:
string(328) "[
{
"id": "01",
"name": "Olivia Mason",
"designation": "System Architect"
},
{
"id": "02",
"name": "Jennifer Laurence",
"designation": "Senior Programmer"
},
{
"id": "03",
"name": "Medona Oliver",
"designation": "Office Manager"
}
]"
為了使這些資料有用,我們可以使用 json_decode() 將 JSON 字串轉換為陣列。在以下程式中使用此函式。
<?php
$Json = file_get_contents("myfile.json");
// Converts to an array
$myarray = json_decode($Json, true);
var_dump($myarray); // prints array
?>
輸出:
array(3) {
=>
array(3) {
["id"]=>
string(2) "01"
["name"]=>
string(12) "Olivia Mason"
["designation"]=>
string(16) "System Architect"
}
=>
array(3) {
["id"]=>
string(2) "02"
["name"]=>
string(17) "Jennifer Laurence"
["designation"]=>
string(17) "Senior Programmer"
}
=>
array(3) {
["id"]=>
string(2) "03"
["name"]=>
string(13) "Medona Oliver"
["designation"]=>
string(14) "Office Manager"
}
}參考文章
https://www.delftstack.com/zh-tw/howto/php/how-to-parse-a-json-file-in-php/
https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/
頁:
[1]