18.19. Writing to Many Filehandles Simultaneously
Problem
You want to send output to more than one file handle; for example, you want to log messages to the screen and to a file.
Solution
Wrap your output with a loop that iterates through your filehandles, as shown in Example 18-4.
Example 18-4. pc_multi_fwrite( )
function pc_multi_fwrite($fhs,$s,$length=NULL) { if (is_array($fhs)) { if (is_null($length)) { foreach($fhs as $fh) { fwrite($fh,$s); } } else { foreach($fhs as $fh) { fwrite($fh,$s,$length); } } } }
Here’s an example:
$fhs['file'] = fopen('log.txt','w') or die($php_errormsg); $fhs['screen'] = fopen('php://stdout','w') or die($php_errormsg); pc_multi_fwrite($fhs,'The space shuttle has landed.');
Discussion
If you don’t want to pass a length argument to
fwrite( )
(or you always want to), you can eliminate
that check from your pc_multi_fwrite( )
. This
version doesn’t accept a $length
argument:
function pc_multi_fwrite($fhs,$s) { if (is_array($fhs)) { foreach($fhs as $fh) { fwrite($fh,$s); } } }
See Also
Documentation on fwrite( )
at
http://www.php.net/fwrite.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.