Recipe 23.15. Writing to Many Filehandles Simultaneously


23.15.1. Problem

You want to send output to more than one filehandle; for example, you want to log messages to the screen and to a file.

23.15.2. Solution

Wrap your output with a loop that iterates through your filehandles, as shown in Example 23-38.

pc_multi_fwrite( )

<?php 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);       }     }   } } $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.'); ?>

23.15.3. 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( ). The version in Example 23-39 doesn't bother with a $length argument.

pc_multi_fwrite( ) without $length

<?php function pc_multi_fwrite($fhs,$s) {   if (is_array($fhs)) {     foreach($fhs as $fh) {       fwrite($fh,$s);     }   } } ?>

23.15.4. See Also

Documentation on fwrite( ) at http://www.php.net/fwrite.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net