if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
} else {
$fh = fopen($myFile, 'w');
fwrite($fh, $message."\n");
}
fclose($fh);
==
if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
} else {
$fh = fopen($myFile, 'w');
}
fwrite($fh, $message."\n");
fclose($fh);
==
$fh = fopen($myFile, (file_exists($myFile)) ? 'a' : 'w');
fwrite($fh, $message."\n");
fclose($fh);
==(因为a
检查文件是否存在,如果不创建它)
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
fclose($fh);
==
file_put_contents($myFile, $message."\n", FILE_APPEND);
...当然,file_put_contents()
是只有更好,如果它是你在给定的手柄执行只写。如果您在同一文件句柄上有任何后续致电fwrite()
的呼叫,最好使用@ Pekka的答案。
缩短它的原因是什么? – Marcus
[fopen的PHP手册](http://php.net/fopen)明确指出'a':*“只打开以便写入;将文件指针放在文件末尾如果文件没有存在,试图创造它。“* - 那是什么问题? – Gordon