How can I read a text file that contains the correct array in php?

I used this to write an array to a text file:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($newStrings, TRUE));
fclose($fp);

Now I want to read it back in php, as if I were reading a regular array? How should I do it? I am new to this and I am in deadline to get something related to this fixed, pls help.

+4
source share
3 answers

var_export()will be valid PHP code that you could includework better than print_r(), but I recommend using JSON / json_encode(). serialize()will also work like JSON, but not portable.

Record:

file_put_contents('file.txt', json_encode($newStrings));

Reading:

$newStrings = json_decode(file_get_contents('file.txt'), true);
+4
source

PHP serialize unserialize .

:

$myArray = ['test','test2','test3'];
$fp = fopen('file.txt', 'w');
fwrite($fp, serialize($myArray));
fclose($fp);

:

file_put_contents('file.txt',serialize($myArray));

:

$myArray = unserialize(file_get_contents('file.txt'));
+1

Use json_encode () or serialize () for the data when writing it, and then use json_decode () or unserialize () for the data when you read it.

To see the differences, check this question: JSON vs. Serialized Array in database

+1
source

All Articles