14

Possible Duplicate:
Print array to a file

How can I write the ouput (for example when I use an array), in a file?, I was trying with this:

    ...
print_r($this->show_status_redis_server());
$status_redis = ob_get_contents();
fwrite($file, $status_redis);
    ...
Community
  • 1
  • 1
itaka
  • 399
  • 1
  • 5
  • 16

2 Answers2

42

print_r() has a second parameters that if passed as TRUE returns the output as a string.

$output = print_r($data, true);
file_put_contents('file.txt', $output);

You could even cosinder using var_export function, as it provides better information about data types. From print_r you can't tell if the variable is NULL of FALSE, but var_export lets use see exactly the data type of a variable.

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
4

print_r($expression [, bool $return = false ]) has optional parameter that identifies you want to return string or echo one.

$str = print_r($desiredVariable, true);
fwrite($handle, $str);

Also I'd use file_put_contents:

$content = print_r($yourVar, true);
file_put_contents('file.log', $content);
Leri
  • 12,367
  • 7
  • 43
  • 60