TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Tips & Tricks (http://www.talkphp.com/tips-tricks/)
-   -   Tip: error_log and arrays (http://www.talkphp.com/tips-tricks/1019-tip-error_log-arrays.html)

Karl 09-06-2007 02:16 PM

Tip: error_log and arrays
 
Output buffering can be used to capture different types of output. For example, lets say your script needs to log an array, we could achieve this like:

PHP Code:

ob_start();
print_r($szArray);
$szLog ob_get_clean();

error_log($szLog); 

What this essentially does is output the array, but becuase we have output buffering on we can catch the output and store it in a varialbe ($szLog) which we can then log to a file (or other source) via the error_log function.

Hope this tip helps someone, it can be very useful for cron type scripts.

Salathe 09-06-2007 02:46 PM

As of PHP 4.3.0, there is an optional second parameter to the print_r function which is a boolean dictating whether the output from print_r is actually output (default) or returned as a string.

Your example can be therefore slightly altered to something more like:
PHP Code:

$aArray = array('one''two''three''four');
// Return print_r output, log to custom log file debug.log
error_log(print_r($aArraytrue), 3'debug.log'); 


Karl 09-06-2007 02:56 PM

well there you go, all that time and I never knew print_r had a second argument.

Im gunna have to update the tip now :)

Salathe 09-06-2007 03:02 PM

No problem, we all oftentimes just stick with what we've been doing from years and years ago. The introduction of little changes (like the inclusion of another argument) is very easy to miss, especially if the 'old' way just works fine also.

P.S. Sorry for coming in and making you edit these tips :p

Karl 09-06-2007 03:07 PM

Lol np, I'm glad you did, I'll certainly be using it from now on! I just wish I didn't edit it now tbh, as it has ruined the flow of the thread. I may have to re-edit it back to how it originally was then post the updated tip below :)

Karl 09-06-2007 03:11 PM

Here's an updated example that shows how it can be used for outputting the debug backtrace to an error log.

PHP Code:

ob_start();
debug_print_backtrace();
$szLog ob_get_clean();

error_log($szLog); 



All times are GMT. The time now is 05:01 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0