PHP - Fonction fwrite ()

La fonction fwrite () peut écrire dans un fichier ouvert. La fonction peut s'arrêter à la fin d'un fichier ou lorsqu'elle peut atteindre une longueur spécifiée, selon la première éventualité. Cette fonction peut renvoyer le nombre d'octets écrits ou faux en cas d'échec.

Syntaxe

int fwrite ( resource $handle , string $string [, int $length ] )

Cette fonction peut écrire le contenu de la chaîne dans le flux de fichier pointé par handle.

Exemple 1

<?php
   $file = fopen("/PhpProject/sample.txt", "w");
   echo fwrite($file, "Hello Tutorialspoint!!!!!");
   fclose($file);
?>

Production

25

Exemple-2

<?php
   $filename = "/PhpProject/sample.txt";
   $somecontent = "Add this to the file\n";

   if(is_writable($filename)) {
      if(!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
       }
   if(fwrite($handle, $somecontent) === FALSE) {
      echo "Cannot write to file ($filename)";
      exit;
   }
   echo "Success, wrote ($somecontent) to file ($filename)";
   fclose($handle);
   
   } else {
      echo "The file $filename is not writable";
   }
?>

Production

Success, wrote (Add this to the file) to file (/PhpProject/sample.txt)