fwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

fwrite寫入文件(可安全用于二進(jìn)制文件)

說明

fwrite(resource $handle, string $string, int $length = ?): int

fwrite()string 的內(nèi)容寫入 文件指針 handle 處。

參數(shù)

handle

文件系統(tǒng)指針,是典型地由 fopen() 創(chuàng)建的 resource(資源)。

string

The string that is to be written.

length

如果指定了 length,當(dāng)寫入了 length 個(gè)字節(jié)或者寫完了 string 以后,寫入就會(huì)停止,視乎先碰到哪種情況。

注意如果給出了 length 參數(shù),則 magic_quotes_runtime 配置選項(xiàng)將被忽略,而 string 中的斜線將不會(huì)被抽去。

返回值

fwrite() 返回寫入的字符數(shù),出現(xiàn)錯(cuò)誤時(shí)則返回 false 。

注釋

注意:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp$string) {
    for (
$written 0$written strlen($string); $written += $fwrite) {
        
$fwrite fwrite($fpsubstr($string$written));
        if (
$fwrite === false) {
            return 
$written;
        }
    }
    return 
$written;
}
?>

注意:

在區(qū)分二進(jìn)制文件和文本文件的系統(tǒng)上(如 Windows) 打開文件時(shí),fopen() 函數(shù)的 mode 參數(shù)要加上 'b'。

注意:

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

注意:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp 
fopen('data.txt''w');
fwrite($fp'1');
fwrite($fp'23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

范例

示例 #1 一個(gè)簡(jiǎn)單的 fwrite() 例子

<?php
$filename 
'test.txt';
$somecontent "添加這些文字到文件\n";

// 首先我們要確定文件存在并且可寫。
if (is_writable($filename)) {

    
// 在這個(gè)例子里,我們將使用添加模式打開$filename,
    // 因此,文件指針將會(huì)在文件的末尾,
    // 那就是當(dāng)我們使用fwrite()的時(shí)候,$somecontent將要寫入的地方。
    
if (!$handle fopen($filename'a')) {
         echo 
"不能打開文件 $filename";
         exit;
    }

    
// 將$somecontent寫入到我們打開的文件中。
    
if (fwrite($handle$somecontent) === FALSE) {
        echo 
"不能寫入到文件 $filename";
        exit;
    }

    echo 
"成功地將 $somecontent 寫入到文件$filename";

    
fclose($handle);

} else {
    echo 
"文件 $filename 不可寫";
}
?>

參見

  • fread() - 讀取文件(可安全用于二進(jìn)制文件)
  • fopen() - 打開文件或者 URL
  • fsockopen() - 打開一個(gè)網(wǎng)絡(luò)連接或者一個(gè)Unix套接字連接
  • popen() - 打開進(jìn)程文件指針
  • file_get_contents() - 將整個(gè)文件讀入一個(gè)字符串