Print array to a file

Atif Mohammed Ameenuddin picture Atif Mohammed Ameenuddin · Apr 13, 2010 · Viewed 354k times · Source

I would like to print an array to a file.

I would like the file to look exactly similar like how a code like this looks.

print_r ($abc); assuming $abc is an array.

Is there any one lines solution for this rather than regular for each look.

P.S - I currently use serialize but i want to make the files readable as readability is quite hard with serialized arrays.

Answer

Gordon picture Gordon · Apr 13, 2010

Either var_export or set print_r to return the output instead of printing it.

Example from PHP manual

$b = array (
    'm' => 'monkey', 
    'foo' => 'bar', 
    'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); // $results now contains output from print_r

You can then save $results with file_put_contents. Or return it directly when writing to file:

file_put_contents('filename.txt', print_r($b, true));