File_put_contents
The file_put_contents function is suitable for automatic writing to a file. Alternatively, you can also use fopen(), which I don't recommend for beginners.
Sample
$file = 'file.txt';$content = 'Content to be saved to file.';file_put_contents($file, $content);
file_put_contents takes 2 parameters:
filenamewhere to write,- the
content of the fileto write.
Note:
file_put_contents()overwrites the file with the latest contents.
Watch out for overwriting
If you save via file_put_contents, beware of overwriting the data. The function will delete all the current content and replace it with the new content. So if you just want to append the text, you can either add it to the beginning or to the end using your own script:
$file = 'file.txt';$content = 'New content.';$oldContent = file_get_contents($file);file_put_contents($file, $content . $oldContent);
So first the file is opened, then the new content is written, and the original content is written after it...
If we want to add the old content before the new, we just need to modify the script slightly:
$file = 'file.txt';$content = New content.';$oldContent = file_get_contents($file);file_put_contents($file, $oldContent . $content);