fopen()发出警告

时间:2015-05-13 19:07:50

标签: php file

我有一个调用fopen()来创建文本文件的脚本。在第一次运行脚本时,它会发出警告:

PHP Warning: fopen(): Filename cannot be empty

据我所知,这是因为文件不存在。我想摆脱警告。

我应该如何使用PHP创建文件。 fopen()是唯一的主要选项,例如文档和所有其他留言胡须吗?

编辑:只是为了澄清

创建并正确写入文件。如果文件不存在,它只会发出警告。

编辑:代码在评论中,但我会把它放在这里。

public function createFile($location = null, $file_name = null)
{
    if (null === $location){
        $location = $this->getFileLocation();
    }
    if (null === $file_name){
        $file_name = $this->getFileName();
    }

    $file_location = realpath($location . DIRECTORY_SEPARATOR . $file_name);

    if (!file_exists($file_location)) {
        $this->setFileHandle(fopen($file_location, 'a'));
    }

    return $this;
}

正如我所说,它运作得很好,只是发出警告。

1 个答案:

答案 0 :(得分:0)

查看fopen的第二个参数,它指示您正在创建的文件句柄的模式。如果文件不存在,某些模式将尝试创建该文件,其他模式将抛出您提到的错误。另请查看file_put_contents

http://php.net/manual/en/function.fopen.php

http://php.net/manual/en/function.file-put-contents.php

如果这没有帮助,请提供完整的工作代码示例。