php - 创建文本文件失败,错误:无法打开流:没有这样的文件或目录
问题描述
我试图在我的 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 中没有这样的文件或目录
(我的错误:这里)
谁能告诉我我的代码有什么问题?
解决方案
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);
推荐阅读
- ansible - 在标准输出上检索 j2 模板文件的内容
- graphql - 如何编写正确的 graphQL 查询以从 gatsby 中的 ghost CMS 中检索/过滤“标签”?
- windows-installer - 来自 InstallShield InstallScript 的主要升级检测
- java - 带有静态方法的 Java 内部类
- go - 在 Go 中将文件放入 amazon s3 后如何获取文件 url?
- r - R:purrr 查找包含命名变量的列表元素
- javascript - 如何在创建 OneDrive 文件夹时修复 BadRequest 错误“无法读取 JSON 请求有效负载”?
- vue.js - 如何可视化 Vue 应用程序的组件层次结构?
- pyglet - 使用 OpenAI 健身房渲染的 draw() 屏幕上未显示 pyglet 标签
- python - 为什么多索引外部索引名称右对齐,而不是左对齐