18.20. Writing to Many Filehandles Simultaneously18.20.1. ProblemYou want to send output to more than one file handle; for example, you want to log messages to the screen and to a file. 18.20.2. SolutionWrap 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.'); 18.20.3. DiscussionIf 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); } } } 18.20.4. See AlsoDocumentation on fwrite( ) at http://www.php.net/fwrite. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|