Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

fwrite

Writes a string to an open file.

Syntax

fwrite(resource $stream, string $data, ?int $length = null): int|false

Parameters

ParameterTypeDescription
$streamresourceA file opened for writing.
$datastringThe data to write.
$length?intOptional. 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
juice

Notes

The 'w' mode erases the file, 'a' appends to the end. For a single write file_put_contents() is simpler.

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.