October 24th 2006 08:50 pm
Print_r to a String
Every PHP developer knows about the print_r function, but for some reason, not many of them know that you can capture the output of print_r and avoid it being printed directly to stdout (the browser in most cases). The print_r function has a little know second argument, true or false, which tells it what to do with the output. By default this is false, which means “don’t return, print to stdout”, if you set this to true, print_r will return a string, which you can do whatever you want with.
<?php
$o = new stdclass();
$o->name = "brien";
$o->website = "http://code-a-day.com/";
$o->date = "today";
print_r($o); // prints to stdout (the browser window)
// a common thing i do is print to the error log:
error_log( print_r($o, true) ); // prints to the default apache error log
// save it in a variable
$data = print_r($o, true);
?>
No Comments yet »
Leave a Reply
You must be logged in to post a comment.