fwrite

(PHP 4, PHP 5, PHP 7)

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

注释

Note:

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;
}
?>

Note:

在区分二进制文件和文本文件的系统上(如 Windows) 打开文件时,fopen() 函数的 mode 参数要加上 'b'。

Note:

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.

Note:

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!
?>

范例

Example #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 不可写";
}
?>

参见

  • fread() - 读取文件(可安全用于二进制文件)
  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开一个网络连接或者一个Unix套接字连接
  • popen() - 打开进程文件指针
  • file_get_contents() - 将整个文件读入一个字符串