Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file put contents with array

Tags:

php

I am using file_put_contents($file, $data); function for putting contents in file, because these files are created on fly with name of sessions, $data is an multi-dimensional array, when i am echoing array it prints out fine but in file no contents get recorded except the word Array

What should i do or is there any other function which automatically creates the file and records the data (array)?

Thank You.

like image 956
Shishant Avatar asked Jun 27 '09 15:06

Shishant


People also ask

How do you add an array to a text file?

If you want to save a variable in a text file, you could use the serialize() / unserialize() functions for that: $data = array(1, 2, 3, ''); $toBeSaved = serialize($data); file_put_contents('somefile. txt', $toBeSaved);

What is File_put_contents?

The file_put_contents() writes data to a file. This function follows these rules when accessing a file: If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename. Create the file if it does not exist. Open the file.

What is the use of File_get_contents in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.


1 Answers

You want to serialize() the array on writting, and unserialize() after reading the file.

$array = array('foo' => 'bar');
file_put_contents('foo.txt', serialize($array));
$array = unserialize(file_get_contents('foo.txt')));

Oh, and I really don't now how you echo'd your array, but echo array('foo' => 'bar'); will always print Array.

like image 181
Philippe Gerber Avatar answered Sep 19 '22 19:09

Philippe Gerber