创建文本文件失败,错误:无法打开流:没有这样的文件或目录

问题描述 投票:0回答:1

我试图在我的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作为文件名来创建文件,但是浏览器页面上的错误提示:

警告:fopen(id_1_29 / 10 / 2019_05:59:57.txt):无法打开流:在......中没有该文件或目录D:\ ProgramFile \ xampp \ htdocs \ pg_api \ create_1.php

(我的错误:here

任何人都可以告诉我我的代码有什么问题吗?

php fopen
1个回答
0
投票
要获得上述文件名:

$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);

© www.soinside.com 2019 - 2024. All rights reserved.