寫入檔案(可安全用於二進制檔案)

fwrite

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

fwrite — 寫入檔案(可安全用於二進制檔案)

說明

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

fwrite() 把 string 的內容寫入 檔案指針 handle 處。

參數

handle

檔案系統指針,是典型地由 fopen() 建立的 resource(資源)。

string

The string that is to be written.

length

如果指定了 length,當寫入了 length 個位元組或者寫完了 string 以後,寫入就會停止,視乎先碰到哪種情況。

注意如果給出了 length 參數,則 magic_quotes_runtime 配置選項將被忽略,而 string 中的斜線將不會被抽去。

返回值

fwrite() 返回寫入的字元數,出現錯誤時則返回 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($fp, substr($string, $written));
        if (
$fwrite === false) {
            return 
$written;
        }
    }
    return 
$written;
}
?>

注意:

在區分二進制檔案和文字檔案的系統上(如 Windows) 打開檔案時,fopen() 函式的 mode 參數要加上 '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 一個簡單的 fwrite() 例子

<?php
$filename 
= 'test.txt';
$somecontent = "新增這些文字到檔案\n";

// 首先我們要確定檔案存在並且可寫。
if (is_writable($filename)) {

    
// 在這個例子里,我們將使用新增模式打開$filename,
    // 因此,檔案指針將會在檔案的末尾,
    // 那就是當我們使用fwrite()的時候,$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 不可寫";
}
?>

參見

Leave a Reply

Your email address will not be published. Required fields are marked *