当文件存在时,PHP file_put_contents
函数工作得很好。如果该文件不存在,我会收到错误"无法打开流:没有这样的文件或目录"。
$file = '../templates/stuff.xml';
if (!file_exists($file)) {$file = '../'.$file;}
$var['xhtml'] = $_POST['post_xhtml'];
$file_contents = serialize($var);
file_put_contents($file,$file_contents);
我用fopen
尝试了同样的事情,并使用正确的标志(w
,w+
并尝试了其他标志)fwrite
但仍然遇到同样的问题:如果文件已经存在,它工作得很好,否则它会给我相同的错误消息。
我知道文件路径是正确的。我正在使用Windows 7进行本地开发。
当文件不存在时,您将在路径前面加上../
,因此您尝试写入:
../../templates/stuff.xml
您确定文件夹../../templates
存在(并且 PHP 可以写入它)吗?
在写入文件之前,需要检查该文件夹是否存在。 尝试使用is_dir()
:
if(is_dir(dirname($file))){
file_put_contents($file, $file_contents);
}