gpt4 book ai didi

php - 将文件写入临时位置

转载 作者:可可西里 更新时间:2023-11-01 13:33:44 26 4
gpt4 key购买 nike

我需要编写一个文件作为 PHP 脚本的一部分(具有自定义文件扩展名的 XML 内容),然后在保存文件后将其附加到我将使用 PHP Mailer 发送的电子邮件中。

电子邮件部分很好,但我以前从来没有用 PHP 写过文件。该文件仅在脚本运行期间需要,不需要永久保存。

如何将文件写入临时位置?

完成文件后是否需要清理临时位置?如果是,怎么办?

最佳答案

为了避免磁盘上实际文件的写入-读取-删除循环,我会使用 php 的内置 php://temp 将所有临时"file"数据存储在内存中和 php://memory IO stream wrappersdocs .

// open a temporary file handle in memory
$tmp_handle = fopen('php://temp', 'r+');
fwrite($tmp_handle, 'my awesome text to be emailed');

// do some more stuff, then when you want the contents of your "file"
rewind($tmp_handle);
$file_contents = stream_get_contents($tmp_handle);

// clean up your temporary storage handle
fclose($tmp_handle);

您永远不必在磁盘上写入或删除文件。另外,请注意使用主题文档中的 php://tempphp://memory 之间的区别:

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

关于php - 将文件写入临时位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9287368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com