【问题标题】:Why does file_put_contents not append data to a file?为什么 file_put_contents 不将数据附加到文件中?
【发布时间】:2013-06-22 09:34:20
【问题描述】:

我有一个复杂的 php4 代码,想用 file_put_contents 向文件中写入一些东西,如下所示:

$iCounter = 0;
foreach blah...
    ... code
    file_put_contents("/tmp/debug28364363264936214", "test" . $iCounter++ . "\n", FILE_APPEND);
    ...code

我正在使用FILE_APPEND 将数据附加到给定的文件中,我确定我打印的内容不包含控制字符,随机数序列确保文件没有在任何其他上下文中使用,并且计数器变量(仅用于打印输出)用于控制调用file_put_contents 的频率。

执行代码,查看刚才看到的文件内容

test8

虽然我期待看到

test1
test2
test3
test4
test5
test6
test7
test8

我的语法有问题吗?也许代码不适用于php4?我还能用什么代替?

附:我正在处理一个非常大、非常古老的 php4 项目,因此无法在 php5 中重新编码该项目。不会在 2 年内...

【问题讨论】:

  • 因为 file_put_contents() 覆盖现有文件,根据文档
  • 它应该可以工作....你使用的是什么版本和操作系统?请注意file_put_contents 是 PHP5 而不是 PHP4 ???
  • 它的 4.4.9-pl0-gentoo 在 2.6.30-gentoo-r4 上。但是如果这个函数只存在于PHP5中,为什么我会得到一些东西呢?我认为它根本不应该工作。
  • @MarkBaker 有一个警告,您可以使用FILE_APPEND 作为第三个参数的标志。直到今天我才知道这一点,这就是为什么我喜欢 SO :)
  • @Alex PHP 文档说(PHP 5)不确定为什么你在 4 中使用它,但也没有指定引入 FILE_APPEND 的日期..

标签: php php4


【解决方案1】:

使用fopen();file_put_contents()是php5。

$file = fopen("/tmp/debug28364363264936214", "a+");
fwrite($file, "test" . $iCounter++ . "\n");
fclose($file);

【讨论】:

    【解决方案2】:

    你可以使用 foreach 它有一个数组输入,它将是一个类似的过程

    for ($iCounter = 1; $iCounter <= 10; $iCounter++) {
    
    $test_var .= "test" . $iCounter . PHP_EOL;
    
    }
    
    
    if (file_exists("/tmp/debug28364363264936214")) {
    
    file_put_contents("/tmp/debug28364363264936214", $test_var, FILE_APPEND);
    
        echo "The file was written";
    } else {
        echo "The file was not written";
    }
    

    php4代码

    if (file_exists("/tmp/debug28364363264936214")) {
    
    $fp = fopen('/tmp/debug28364363264936214', 'a');
    fwrite($fp, $test_var);
    fclose($fp);
    
        echo "The file was written";
    } else {
        echo "The file was not written";
    }
    

    您的代码可能在 php4 中,但如果使用您应该使用的 php5,它应该在 php5 中工作。你只需要重新编码错误。

    【讨论】:

      【解决方案3】:

      如果要追加数据,请执行以下操作

       $file = "yourfile.txt";
       $data = file_get_contents($file);
       $data =  $data . $newdata;
       file_put_contents($file, $data);
      

      【讨论】:

      • 但是为什么我的代码不起作用?或者为什么它对 php4 有点作用?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      相关资源
      最近更新 更多