PHP File Write
From w3cyberlearnings
Contents |
PHP Write Content to a file
Write content to a file is possible by using the fwrite() function. However, you need to create a file handler by using fopen() function and with the 'w' for its second parameter. Please see the example for detail.
Syntax fwrite
- w: write to a file (when a file not existed create a new one)
- filehandle: file handle create by fopen
- content: content to write to a file
filehandle = fopen(filename,'w'); fwrite(filehandle, content);
Example 1
<?php $file_handler = fopen('test1.txt', 'w') or exit('unable to read the file'); $content = 'Peace from your heart'; fwrite($file_handler, $content); fclose($file_handler); ?>
Output (test1.txt)
Peace from your heart
Example 2
<?php $file_handler = fopen('test1.txt', 'w') or exit('unable to read the file'); $name = array('John', 'Bob Mark', 'Kim', 'Dara'); foreach ($name as $n) { $content = '<br/>'.$n.'<br/>'; fwrite($file_handler, $content); } fclose($file_handler); ?>
Output (test1.txt)
<br/>John<br/><br/>Bob Mark<br/><br/>Kim<br/><br/>Dara<br/>