The fwrite Function

The fwrite function writes data to a file opened with fopen. The function takes a file pointer as its first parameter, a string to write as the second, and an optional maximum number of bytes to write as the third.

Syntax

phpfwrite(resource, string, [length]);

Example

Let's write a string to a file:

php<?php
  $file = fopen('test.txt', 'w');
  fwrite($file, 'text');
  fclose($file);
?>

Example

Let's write only the first 2 characters:

php<?php
  $file = fopen('test.txt', 'w');
  fwrite($file, 'text', 2);
  fclose($file);
?>

Example

Let's append text to the end of the file:

php<?php
  $file = fopen('test.txt', 'a');
  fwrite($file, '!');
  fclose($file);
?>

See Also