PHP修改文件:文件未被修改,但没有错误消息打印到控制台

时间:2015-04-21 20:03:41

标签: php fwrite

我一直在网上搜索一段时间,但我真的找不到任何有用的东西。我找不到代码中的错误,而且我没有在控制台中找到任何错误。我可以打开我的文件,我改变它的字符串,我没有写任何错误,但文件没有被修改。我错过了什么?

$file = $_SERVER['DOCUMENT_ROOT']."/files/wsplaetze.OLD.txt";
$newline = "";
$handle = fopen($file, "r+");
$counter = 0;
if($handle) {
    while(($line = fgets($handle)) !== false) {
        ++$counter;
        $parts = explode(' ', $line);
        $to_add = $parts[0] . " " . intval($parts[1]) . '\n';
        foreach($ws_array as $ws) {
            if($parts[0] == $ws) {
                $anzahl = intval($parts[1])-1;
                $to_add = $parts[0] . " " .  $anzahl . '\n';
            }
        }
        $newline .= $to_add;
    }

} else {
    debug_to_console(error_get_last()."ERROR");
}

debug_to_console("length ".$counter);
debug_to_console($newline);

if(!fwrite($handle, $newline)) {
    debug_to_console("Error writing to file:  ".$file);
} else {
    debug_to_console("Great! Everything is fine! This is the file you wrote to: ".$file);
}
fclose($handle);

文件本身由与其关联的ID和数字组成,按空格分隔,如下所示:

ab 12
abs 23
skd 12

我做错了什么?我真的不知道在哪里看,因为我没有收到上面的任何错误消息! 我可以读取文件(正确!),所以文件名似乎也是写的?但话说回来,没有什么变化......我真的很困惑!

编辑:使用评论中的帮助,代码现在正常工作!!该文件必须重新打开!这样旧的内容就会被覆盖!我改成了这个:

$file = $_SERVER['DOCUMENT_ROOT']."files/wsplaetze.OLD.txt";
$newline = "";
  $handle = fopen($file, "r+");
  $counter = 0;
        if($handle) {
            while(($line = fgets($handle)) !== false) {
                ++$counter;
                $parts = explode(' ', $line);
                $to_add = $parts[0] . " " . intval($parts[1]) . "\n";
                foreach($ws_array as $ws) {
                    if($parts[0] == $ws) {
                        $anzahl = intval($parts[1])-1;
                        $to_add = $parts[0] . " " .  $anzahl . "\n";
                    }
                }
                $newline .= $to_add;
            }
    fclose($handle);

        } else {
            debug_to_console(error_get_last()."ERROR");
        }


    $filew = fopen($file, "w");
    if($filew) {
        fwrite($filew, $newline);
    }
    fclose($filew);

1 个答案:

答案 0 :(得分:0)

我假设您已将要写入文件的内容存储到$ content变量中。

$file = $_SERVER['DOCUMENT_ROOT']."/files/wsplaetze.OLD.txt";

// @ prevents errors but allows the function to return true or false

if(@file_put_contents($file, $content, LOCK_EX)){
    debug_to_console("Great! Everything is fine! This is the file you wrote to: ".$file);
}else{
    debug_to_console("Error writing to file:  ".$file);
}