当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。