php 用php清空文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4944388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:24  来源:igfitidea点击:

Emptying a file with php

php

提问by Chris Mccabe

Possible Duplicate:
PHP: Is there a command that can delete the contents of a file without opening it?

可能的重复:
PHP:是否有一个命令可以在不打开文件的情况下删除文件的内容?

How do you empty a .txt file on a server with a php command?

如何使用 php 命令清空服务器上的 .txt 文件?

回答by Artefacto

Here's a way to only emptying if it already exists and that doesn't have the problem of using file_exists, as the the file may cease to exist between the file_existscall and the fopencall.

这是一种仅在它已经存在并且没有使用问题的情况下才清空的方法file_exists,因为文件可能在file_exists调用和fopen调用之间不存在。

$f = @fopen("filename.txt", "r+");
if ($f !== false) {
    ftruncate($f, 0);
    fclose($f);
}

回答by Dan Grossman

Write an empty string as the content of filename.txt:

写一个空字符串作为 的内容filename.txt

file_put_contents('filename.txt', '');

回答by riha

$fh = fopen('filename.txt','w'); // Open and truncate the file
fclose($fh);

Or in one line and without storing the (temporary) file handle:

或者在一行中并且不存储(临时)文件句柄:

fclose(fopen('filename.txt','w'));

As others have stated, this creates the file in case it doesn't exist.

正如其他人所说,这会创建文件,以防它不存在。

回答by Ferdinand Beyer

Just open it for writing:

只需打开它进行写作:

if (file_exists($path)) {     // Make sure we don't create the file
    $fp = fopen($path, 'w');  // Sets the file size to zero bytes
    fclose($fp);
}

回答by BlueDog

First delete it using unlink()and then just create a new empty file with the same name.

首先使用删除它unlink(),然后创建一个具有相同名称的新空文件。

回答by álvaro González

With ftruncate(): http://php.net/ftruncate

ftruncate()http: //php.net/ftruncate

回答by Ankur

you can use the following code

您可以使用以下代码

`

`

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);

` It will just override your file content to blank

` 它只会将您的文件内容覆盖为空白