當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP fwrite()用法及代碼示例



fwrite() 函數可以寫入打開的文件。該函數可以在文件末尾或到達指定長度時停止,以先到者為準。此函數可以返回寫入的字節數或失敗時返回 false。

用法

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

該函數可以將字符串的內容寫入句柄指向的文件流中。

示例1

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

輸出

25

示例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";
   }
?>

輸出

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

相關用法


注:本文由純淨天空篩選整理自 PHP - Function fwrite()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。