tags:

views:

102

answers:

5

Hello,

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.

A: 

You could serialize the array and then userialize it after you load the file back in. You could also encode the array as a JSON object with json_encode and write to a .json file.

Typeoneerror
A: 

If you want it to be readable, you could do:

<?php
ob_start();
print_r($data);
$textualRepresentation = ob_get_contents();
ob_end_clean();

file_put_contents($file, $textualRepresentation);
?>
$textualRepresentation = print_r($data, true); would just do fine :-)
Philippe Gerber
Haha... didn't know that. Thanks :)
+3  A: 

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.

Philippe Gerber
i am sorry for using the wrong term, but i am using print_r for displaying my array
Shishant
just a note, your missing a ) on the 2nd line
Uberfuzzy
thx! fixed it. :-)
Philippe Gerber
A: 

You can set up a recursive function that can traverse each member of an array, check if it is itself an array, and if so call the function again on this member, and if not just print out its contents. Like this:

function file_put_contents_deep( $file, $data) {
  if ( is_array( $data ) {
    foreach ( $data as $item ) {
      if (is_array( $item ) {
        file_put_contents_deep( $file, $item );
      else {
        file_put_contents( $file, $item);
      }
    }
  } else {
    file_put_contents( $file, $data );
  }
}
alxp
A: 

Definetelly you can use var_export function:

$contents = var_export($array, true);

file_put_contents('foo.txt', "<?php\n {$contents};\n ?>");
inakiabt