<?php
$filename = 'file.txt';
$word = "你好!\r\nwebkaka"; //双引号会换行 单引号不换行
file_put_contents($filename, $word);
?>
<?php
$filename = 'file.txt';
$word = "你好!\r\nwebkaka"; //双引号会换行 单引号不换行
$fh = fopen($filename, "w"); //w从开头写入 a追加写入
echo fwrite($fh, $word);
fclose($fh);
?>
常见问题: Warning: fopen(file.txt) [function.fopen]: failed to open stream: Permission denied 当写入文件时,有时会遇到上述问题,这是因为文件没有写权限的原因。为了避免这个错误的出现,在写入文件时需要判断下文件是否可写,这需要用到is_writable()这个函数。实例代码如下:
<?php
$filename = 'file.txt';
if (is_writable($filename)) {
echo file_put_contents($filename, "This is another something.", FILE_APPEND);
} else {
echo "文件 $filename 不可写";