Create text file failed, error: failed to open stream: No such file or directory

Create text file failed, error: failed to open stream: No such file or directory

我试图在我的 xampp 目录中创建文件:

path : D:\ProgramFile\xampp\htdocs\pg_api

我已经创建了一个 php 文件,create.php

这是代码:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

我运行代码和文件生成成功,现在我想要创建一个文本文件,名称来自变量:

这是我试过的:

<?php

$currentdate = date('d/m/Y_H:i:s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";

$myfile = fopen($filename, "w") or die("Unable to open file!");

$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

?>

我希望创建的文件以 $filename 作为文件名,但浏览器页面上出现错误:

Warning: fopen(id_1_29/10/2019_05:59:57.txt): failed to open stream: No such file or directory in D:\ProgramFile\xampp\htdocs\pg_api\create_1.php

(我的错误:here

谁能告诉我我的代码有什么问题?

Windows 不允许像 / 这样的特殊字符作为文件名(即使在 linux 中也不安全)。不仅如此,我宁愿使用 id_1_29-10-2019_05-59-57.txt

这样的文件名

实现上面的文件名:

$currentdate = date('d-m-Y_H-i-s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";

$myfile = fopen($filename, "w") or die("Unable to open file!");

$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);