如何在 PHP 中生成 JSON 檔案

Minahil Noor 2020年6月25日
如何在 PHP 中生成 JSON 檔案

在本文中,我們將介紹在 PHP 中生成 .json 檔案的方法。

  • 使用 file_put_contents() 函式

在 PHP 中使用 file_put_contents() 函式生成一個 json 檔案

內建函式 file_put_contents() 可以將內容寫入 PHP 檔案中。它搜尋要寫入的檔案,如果不存在所需的檔案,它將建立一個新檔案。我們可以使用這個函式來建立一個 .json 檔案。使用此函式的正確語法如下

file_get_contents($pathOfFile, $info, $customContext, $mode);

該函式接受四個引數。這些引數的詳細資訊如下。

引數 描述
$pathOfFile 強制性的 它指定檔案的路徑
$info 強制性的 它指定你希望寫入檔案的資訊或資料。它可以是一個字串。
$customContext 可選的 它用於指定自定義上下文
$mode 可選的 它指定將資料寫入檔案的方式。它可以是 FILE_USE_INCLUDE_PATH,FILE_APPEND 和 LOCK_EX。

如果成功,此函式返回寫入檔案的位元組數,否則返回 false

下面的程式將建立一個新的 .json 檔案並將 JSON 資料儲存到其中

<?php 
  
// data strored in array
$array = Array (
    "0" => Array (
        "id" => "01",
        "name" => "Olivia Mason",
        "designation" => "System Architect"
    ),
    "1" => Array (
        "id" => "02",
        "name" => "Jennifer Laurence",
        "designation" => "Senior Programmer"
    ),
    "2" => Array (
        "id" => "03",
        "name" => "Medona Oliver",
        "designation" => "Office Manager"
    )
);

// encode array to json
$json = json_encode($array);
$bytes = file_put_contents("myfile.json", $json); 
echo "The number of bytes written are $bytes.";
?>

我們使用 json_encode() 函式將儲存在陣列中的資料轉換為 JSON 字串。資料轉換為 JSON 字串後,file_put_contents() 函式將建立一個 JSON 檔案並將資料寫入其中。輸出顯示位元組數,這意味著資料已成功寫入。

輸出:

The number of bytes written is 207.

相關文章 - PHP JSON