4

I used this to write a array into 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 just like i would read a normal array? how do i do it? I'm fairly new to this and im currently on a deadline to get something related tot this fixed, pls help.

Aman
  • 155
  • 1
  • 11

3 Answers3

4

var_export() would be valid PHP code that you could then include and work better than print_r(), but I recommend using JSON / json_encode(). serialize() would also work similar to JSON but isn't portable.

Write:

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

Read:

$newStrings = json_decode(file_get_contents('file.txt'), true);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

Use PHP serialize and unserialize to do this.

Writing to file:

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

Or slimmer:

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

Reading it again:

$myArray = unserialize(file_get_contents('file.txt'));
Marc
  • 3,683
  • 8
  • 34
  • 48
1

Use json_encode() or serialize() on the data when you write it and then use json_decode() or unserialize() on the data when you have read it.

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

Community
  • 1
  • 1
sleepless_in_seattle
  • 2,132
  • 4
  • 24
  • 35