如何从文本文件读取数组?
问题描述:
我已经使用php中的file_put_contents()将数组存储在txt文件中,而php数组在文本文件中写入成功同时又如何将文本文件读入php中?
I have stored array in txt file using file_put_contents() in php, php array write successfullu in text file as same time how to read that text file into php?
<?php
$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));
?>
上述php成功写入文本文件.我想在php中读取该文本文件?
The above php write text file in successfully. i want read that text file in php?
答
如果计划在数组中重用这些相同的值,则可以在创建该数组文件时使用var_export
.
If you plan on reusing those same values inside the array, you could use var_export
on creating that array file instead.
基本示例:
$arr = array('name','rollno','address');
file_put_contents('array.txt', '<?php return ' . var_export($arr, true) . ';');
然后,当需要使用这些值时,只需使用include
:
Then, when the time comes to use those values, just use include
:
$my_arr = include 'array.txt';
echo $my_arr[0]; // name
或者只使用一个简单的JSON
字符串,然后进行编码/解码:
Or just use a simple JSON
string, then encode / decode:
$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