fwrite
Writes a string to an open file.
Syntax
fwrite(resource $stream, string $data, ?int $length = null): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $stream | resource | A file opened for writing. |
| $data | string | The data to write. |
| $length | ?int | Optional. The maximum number of bytes. |
Return value
int|falseThe number of bytes written, or `false`.
Examples
Writing several lines:
<?php
$file = sys_get_temp_dir() . '/ref-fwrite.txt';
$handle = fopen($file, 'w');
foreach (['tea', 'coffee', 'juice'] as $item) {
fwrite($handle, $item . "\n");
}
fclose($handle);
echo file_get_contents($file);Output:
tea
coffee
juiceNotes
The 'w' mode erases the file, 'a' appends to the end. For a single write file_put_contents() is simpler.
See also
- fopen — Opens a file for reading or writing piece by piece.
- file_put_contents — Writes data to a file.
- fclose — Closes an open file.
Related recipes
In the tutorial
- Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.