Jump to: navigation, search

PHP File Write

From w3cyberlearnings

Contents

PHP Write Content to a file

Write content to a file is possible by using the fwrite() function. However, you need to create a file handler by using fopen() function and with the 'w' for its second parameter. Please see the example for detail.

Syntax fwrite

  • w: write to a file (when a file not existed create a new one)
  • filehandle: file handle create by fopen
  • content: content to write to a file
filehandle = fopen(filename,'w');
fwrite(filehandle, content);

Example 1

<?php

$file_handler = fopen('test1.txt', 'w')
		  or exit('unable to read the file');
$content = 'Peace from your heart';
fwrite($file_handler, $content);
fclose($file_handler);
?>

Output (test1.txt)

Peace from your heart

Example 2

<?php

$file_handler = fopen('test1.txt', 'w')
		  or exit('unable to read the file');
$name = array('John', 'Bob Mark', 'Kim', 'Dara');
foreach ($name as $n) {
	$content = '<br/>'.$n.'<br/>';
	fwrite($file_handler, $content);
}
fclose($file_handler);
?>

Output (test1.txt)

<br/>John<br/><br/>Bob Mark<br/><br/>Kim<br/><br/>Dara<br/>

Related Links


  1. PHP File Linux vs. Windows
  2. PHP File Information
  3. PHP File Create
  4. PHP File Close
  5. PHP File Read
  6. PHP File Read Reverse
  1. PHP File Write
  2. PHP File Write to end or append to
  3. PHP File Write at Beginning
  4. PHP File Write at specific location
  5. PHP File Truncate
  6. PHP File Replace a specific word
  1. PHP File Replace a specific word with associative array
  2. PHP File Copy File
  3. PHP File Copy Reverse
  4. PHP File Search within file
  5. PHP File Delete File
  6. PHP File Template
  1. PHP File Email Template
  2. PHP File Template with MySQL
  3. PHP File Access with MySQL
Navigation
Web
SQL
MISC
References