我在 php 中使用 file_put_contents() 将数组存储在 txt 文件中,php 数组在文本文件中写入成功,同时如何将该文本文件读入 php?
<?php
$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));
?>
上面的php写入文本文件成功。我想在 php 中读取该文本文件?
最佳答案
如果您计划在数组中重复使用这些相同的值,则可以使用 var_export
来创建该数组文件。
基本示例:
$arr = array('name','rollno','address');
file_put_contents('array.txt', '<?php return ' . var_export($arr, true) . ';');
然后,当需要使用这些值时,只需使用 include
:
$my_arr = include 'array.txt';
echo $my_arr[0]; // name
或者只使用一个简单的 JSON
字符串,然后编码/解码:
$arr = array('name','rollno','address');
file_put_contents('array.txt', json_encode($arr));
然后,当你需要的时候:
$my_arr = json_decode(file_get_contents('array.txt'), true);
echo $my_arr[1]; // rollno
关于php - 如何从文本文件中读取数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603651/