方法:首先用“json_decode(字符串,true)”語句將JSON格式轉(zhuǎn)換成數(shù)組格式;然后用“數(shù)組[元素]="值"”語句來修改數(shù)據(jù);最后用“json_encode(數(shù)組)”語句將修改后的數(shù)組轉(zhuǎn)換成json格式即可。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
// 追加寫入用戶名下文件 $code="001";//動態(tài)數(shù)據(jù) $json_string = file_get_contents("text.json");// 從文件中讀取數(shù)據(jù)到PHP變量 $data = json_decode($json_string,true);// 把JSON字符串轉(zhuǎn)成PHP數(shù)組 $data[$code]=array("a"=>"as","b"=>"bs","c"=>"cs"); $json_strings = json_encode($data); file_put_contents("text.json",$json_strings);//寫入 //修改 $json_string = file_get_contents("text.json");// 從文件中讀取數(shù)據(jù)到PHP變量 $data = json_decode($json_string,true);// 把JSON字符串轉(zhuǎn)成PHP數(shù)組 $data["001"]["a"]="aas"; $json_strings = json_encode($data); file_put_contents("text.json",$json_strings);//寫入
推薦:《2021年P(guān)HP面試題大匯總(收藏)》《php視頻教程》