php写入读取json文件的数组内容
2020-07-03 网络
php以json文件形式将数组存入本地并读取打印出来,以下为源码:
// 生成一个PHP数组 $data = array ( 0 => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), 1 => array ( 1,2,3,4,5,6), 2 => array ( "first",3 => "second","third") ); $data[3]['id']='30'; $data[3]['content']="php content 31"; //打印二维数组的内容 print_r ($data); // 把PHP数组转成JSON字符串 $json_string = json_encode($data); // 写入文件 if(file_put_contents('test.json', $json_string)){ print('<br>写入文件成功!<br>'); } else { print('<br>写入文件失败!<br>'); } // 从文件中读取数据到PHP变量 @$json_string = file_get_contents('test.json'); //行首加@以隐藏错误提示 if($json_string){ // 把JSON字符串转成PHP数组 $data = json_decode($json_string, true); // 打印数组内容 print_r($data); } else { print('<br>json文件不存在.'); }
这是写入本地json文件中的内容
[{"a":"orange","b":"banana","c":"apple"},[1,2,3,4,5,6],{"0":"first","3":"second","4":"third"},{"id":"30","content":"php content 31"}]
浏览器运行显示的内容
Array ( [0] => Array ( [a] => orange [b] => banana [c] => apple ) [1] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) [2] => Array ( [0] => first [3] => second [4] => third ) [3] => Array ( [id] => 30 [content] => php content 31 ) ) 写入文件成功! ( [0] => Array ( [a] => orange [b] => banana [c] => apple ) [1] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) [2] => Array ( [0] => first [3] => second [4] => third ) [3] => Array ( [id] => 30 [content] => php content 31 ) )