Ahmad Fouad
Ahmad Fouad

Reputation: 4107

How to put an array into a file?

I do this to get file content into array:

$array = file('sample.txt', FILE_IGNORE_NEW_LINES);

How to reverse this? If I have the array already how to write it to a file, each value in a seperate line.

Upvotes: 3

Views: 12931

Answers (4)

Silvio Delgado
Silvio Delgado

Reputation: 6975

You can serialize the array or try this:

$result = implode(PHP_EOL, $array);
file_put_contents('sample.txt', $result);

Upvotes: 0

ultra
ultra

Reputation: 141

I suggest you to use file_get_contents function instead of file(). Using that function you will get a string, and that can be easily written to file by file_put_contents.

To make a string from the array you can use implode:

$string = implode("\n", $array);
file_put_contents("file.txt", $string);

To store an array you have to serialize it to make a string.

Upvotes: 2

Glass Robot
Glass Robot

Reputation: 2448

serialize the array before writing and unserialize to get the array back.

Upvotes: 1

alexn
alexn

Reputation: 58962

It would not make sense to put each value on a different row. You're probably looking for serialize.

If you really want each element on it's own line, you could use implode:

$str = implode("\n", $array);
file_put_contents($file, $str);

Upvotes: 9

Related Questions