我尝试使用 PHP 中的 file_get_contents,但它不起作用。
这是我的代码:
$filename = "/opt/gemel/test.txt";
if($filecontent = file_get_contents($filename)){
$nom = fgets(STDIN);
file_put_contents($filename, $nom, FILE_APPEND);
}
else
echo "fail";
而我的文件 test.txt 是空的。 (0 个八位字节)。他存在,但他是空的。
当我向其中写入内容时,我的代码可以完美运行,但如果他为空,我的代码回显“失败”
为什么,为什么他打不开文件 text.txt ?
最佳答案
file_get_contents
函数返回文件中的字符串。如果文件不包含任何数据,则 file_get_contents
返回一个空字符串。如果您尝试 var_dump('' == false);
,您将得到 true
。因此,即使可以读取文件,文件内容的计算结果也是 false
。
如果您使用这一行,您的代码应该可以工作:
if($filecontent = file_get_contents($filename) !== false){
编辑;链接到 Comparison operators 的文档.
关于php - 带有空文件的 file_get_contents 无法正常工作 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615003/