views:

66

answers:

4

Hi,

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 serialie but i want to make the files readable as readability is quite hard with serialized arrays.

+6  A: 

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));
Gordon
+2  A: 

You could try:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array));
Sarfraz
+2  A: 

Just use print_r ; ) Read the documentation:

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.

So this is one possibility:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($array, TRUE));
fclose($fp);
Felix Kling
i used to think print_r is a construct
atif089
+3  A: 

file_put_contents($file, print_r($array, true), FILE_APPEND)

binaryLV
+1 . Maybe he doesn't require extra parameter FILE_APPEND.
zaf
Sure. Added the flag just to emphasize that it is possible to append, not only overwrite.
binaryLV