Writing to Files
file_put_contents('file.txt',
''> This text file contains\nsome random text.
<'');
|
Writing to files is as easy as reading from themif you are using PHP 5 or higher. Then, the function file_put_contents() writes data directly to a file, and this is binary-safe. After calling the function, the file is closed. The code writes data into a file.
Writing Data into a File (file_put_contents.php)
<?php
file_put_contents('file.txt',
''> This text file contains\nsome random text.
<'');
echo 'File written.';
?>
However, the preceding code overwrites the existing file. If you want to append data (therefore emulating file mode a), you first have to read in the file's data.
Appending Data to a File (file_append_contents.php)
<?php
function file_append_contents($filename, $data) {
$olddata = @file_get_contents($filename);
return file_put_contents($filename,
''$olddata$data'');
}
file_append_contents('file.txt',
"\n> This text file contains\neven more random
text. <");
echo 'Data appended to file';
?>
It is even easier to provide a third parameter to file_put_contents() to append data instead of overwriting files:
file_put_contents($filename, $data, FILE_
APPEND);
|
However, this all fails when a PHP version below 5.0.0 is used because the function file_put_contents() does not exist in earlier versions. It is, however, possible to emulate the behavior of file_put_contents() for older PHP versions. This works similarly to reading from a file with fopen(), fgets(), and fclose(). For writing, just one more function is required: fwrite() writes data to a file handle. The following code implements this approach. Using function_exists(), you can check whether the function file_put_contents() already exists. If not, you can write it.
Using file_put_contents() with All Relevant PHP Versions (file_put_contents_compatible.php)
<?php
if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $content)
{
if ($fp = @fopen($filename, 'w')) {
$result = fwrite($fp, $content);
fclose($fp);
return $result;
} else {
return false;
}
}
}
file_put_contents('file.txt',
"\n> This text file contains\nsome random text.
<");
echo 'Data written to file.';
?>
|