php - 有没有可能做比这更短的 "if file exists then append, else create new file"

标签 php

我有以下代码,但我试图将其缩短一两行,因为我认为 if 是不必要的。有什么办法可以将下面的代码缩短为单行吗?

 if(file_exists($myFile))
    {
        $fh = fopen($myFile, 'a');
        fwrite($fh, $message."\n");
    }
    else
    {
        $fh = fopen($myFile, 'w');
        fwrite($fh, $message."\n");
    }
    

最佳答案

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 的回答。

关于php - 有没有可能做比这更短的 "if file exists then append, else create new file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8165902/

相关文章:

php - 大文件的 cURL SSL 错误

php - 在 PHP/MySQL 中使用 Week(Date) 时,如何将一周的第一天设置为星期一?

php - Codeigniter MySQL 将结果分组为多维数组

javascript - 没有地址栏的弹出窗口

php - 为什么我在 PHP 中有一个 "Parse error: syntax error, unexpected T_PUBLIC"?

php - 乘法运算符会导致SQL注入(inject)吗?

php - 从文本 block 中提取和删除 URL

php - Elasticsearch AND/BOOL 条件 + PHP

javascript - 如何突出显示 ChartJS 中的特定数据点,其中我的数据来自 json 数组?

php - xpath查找非空链接