开发者

How to put an array into a file?

I d开发者_JS百科o 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.


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);


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.


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


You can serialize the array or try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜