Home  >  Article  >  Backend Development  >  Usage of PHP function fwrite

Usage of PHP function fwrite

PHP中文网
PHP中文网Original
2017-06-05 11:25:493335browse

PHP function fwrite -- write to file (safe for binary files)

Description

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

PHP function fwrite writes the content of string into the file pointer handle. If length is specified, writing will stop when length bytes have been written or when the string has been written, whichever occurs first.

v returns the number of characters written, or FALSE if an error occurs.

Note that if the length parameter is given, the magic_quotes_runtime configuration option will be ignored and slashes in the string will not be stripped.

Note: When opening a file on a system that distinguishes between binary files and text files (such as Windows), the mode parameter of the fopen() function must be added with 'b'.

Example 1. A simple example of PHP function fwrite

< ?php  
$filename = &#39;test.txt&#39;;  
$somecontent = "添加这些文字到文件\n";  
// 首先我们要确定文件存在并且可写。  
if (is_writable($filename)) {  
// 在这个例子里,我们将使用添加模式
打开$filename,  
// 因此,文件指针将会在文件的开头,  
// 那就是当我们使用fwrite()的时候,
$somecontent将要写入的地方。  
if (!$handle = fopen($filename, &#39;a&#39;)) {   
echo "不能打开文件 $filename";  
exit;  
}  
// 将$somecontent写入到我们打开的文件中。  
if (fwrite($handle, $somecontent) 
=== FALSE) {  
echo "不能写入到文件 $filename";  
exit;  
}  
echo "成功地将 $somecontent 写入
到文件$filename";  
fclose($handle);  
} else {  
echo "文件 $filename 不可写";  
}  
?>

The above is the relevant usage of PHP function fwrite.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn