平常我們要修改 json 內容都是透過 API 的方式,利用 API 去讀取與修改 DB 的內容,但如果想要直接修改不透過 DB 的話可以參考以下方式。

這邊都是使用 file_get_contents() 取得內容與使用 file_put_contents() 修改內容,但需要再取得內容與寫入內容時候做一下型別的轉換:

1. 使用 JSON 轉換

取得內容:

$data = file_get_contents( 'data.json' );
$arr = json_decode( $data, true );

修改內容:

$arr = array( [...] );
file_put_contents( 'data.json', json_encode( $arr ) );

 

2. 使用 serialize 轉換

取得內容:

$data = file_get_contents( 'data.json' );
$arr = unserialize( $data );

設定內容:

$arr = array( [...] );
file_put_contents( 'data.json', serialize( $arr ) );

 

雖然我這邊副檔名是用  json,但其實這邊用 txt 之類的應該結果也都一樣。

參考:
Writing Array to File in php And getting the data