Hide options

Write to a file with PHP

Example how to write to a file using PHP. When the file does not exist it will be created
<?php 
   $file = "filename.txt"; 
   $handle = fopen($file, 'w'); // Open the file for writing

   // Write data to the file
   $data = "line 1n"; 
   fwrite($handle, $data); 
   $data = "line 2n"; 
   fwrite($handle, $data); 

   echo "Data Written"; 

   // Allways close the file when ready
   fclose($handle); 
?>


Description

running this script the second time will erase the first generated file. If a file is allready generated and we want to append data to the file use:

fopen($file,'a');


Top