Print array to a file
Solution 1:
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));
Solution 2:
Just use print_r
; ) Read the documentation:
If you would like to capture the output of
print_r()
, use thereturn
parameter. When this parameter is set toTRUE
,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);
Solution 3:
You could try:
$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));
Solution 4:
file_put_contents($file, print_r($array, true), FILE_APPEND)
Solution 5:
Quick and simple do this:
file_put_contents($filename, var_export($myArray, true));