PHP fwrite()和fputs()函数用于将数据写入文件。 要将数据写入文件,需要使用w,r+,w+,x,x+,c或c+等这些模式。
PHP写文件 - fwrite()函数
PHP fwrite()函数用于将字符串的内容写入文件。
语法
int fwrite ( resource $handle , string $string [, int $length ] )
示例
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
echo "File written successfully";
?>
执行上面代码得到以下结果(打开data.txt ) -
welcome to php file write
PHP覆盖文件
如果再次运行上面的代码,它将擦除文件的前一个数据并写入新的数据。 下面来看看看只将新数据写入data.txt文件的代码。
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);
echo "File written successfully";
?>
执行上面代码得到以下结果(打开data.txt ) -
hello
PHP追加到文件
如果使用a模式,则将不会删除文件的数据。而是将在文件的末尾写入数据。 在下一个主题文章中我们将介绍如何把数据追加到文件中。
