繁体   English   中英

如何使用 php 将回显中的所有变量结果保存到 txt 文件中?

[英]How can i save all the variable results from a echo into a txt file using php?

我写了一个生成随机令牌的 php 脚本,我想把这些令牌 output 放到一个 .txt 文件中。

下面是代码:

do {

    $token = bin2hex(random_bytes(2));

    echo("token: $token");

    $myfile = fopen("output.txt", "w+") or die("Unable to open file!");
    fwrite($myfile, $token);
    fclose($myfile);

} while ($token != "e3b0");

它回显多个标记,直到echo = e3b0,但是当我尝试将结果写入txt文件时,它只写入“e3b0”,这是将“echo”的所有结果写入txt文件的一种方式吗?

在我看来,最有效的方法是将所有事情都做足够的时间。 这意味着我们必须循环并生成代码,但我们只需要写入文件一次,与 echo 相同。

$code = "start value";
while ($code != "e3b0"){
    $arr[] = $code = bin2hex(random_bytes(2));
}

echo $str = implode("\n", $arr);
file_put_contents("output.txt", $str);

这是做所有事情的时间,以及更优化的代码。
但是,如果您在浏览器中运行它,那么它不会 output 它们在屏幕上的单独行中,仅在 txt 文件中。 但是,如果您打开源代码,它将位于不同的行上。
那是因为我没有在 implode 中使用 br 标签。

编辑:在原始 OP 问题中从未问过效率。 正在编辑这篇文章以包括效率,即无需重新打开和关闭文件。

您对w+的使用将始终将文件指针放在文件的开头并在进程中截断文件。 因此,您总是以最后写入的值结束。

fopen w+上的php.net

Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file does not exist, attempt to create it.

使用您现有的代码,解决方案如下:

$myfile = fopen("output.txt", "a+") 或 die("无法打开文件;");

do {

$token = bin2hex(random_bytes(2));

echo("token: $token");


fwrite($myfile, $token);


} while ($token != "e3b0");

fclose($myfile);

同一文档中的a+说:

Open for reading and writing; place the file pointer at the end of the file. 
If the file does not exist, attempt to create it. In this mode, fseek() 
only affects the reading position, writes are always appended.

来源: https://www.php.net/manual/en/function.fopen.php

修正:

正如@andreas 所提到的,在循环内重复打开和关闭文件是不必要的(也没有效率)。 由于您正在追加,因此您可以在循环开始之前用a+打开一次; 并在循环结束后关闭它。

就写入文件的标记之间有分隔符而言,回车(换行符)是一个不错的选择。 通过这种方式,您可以减少以编程方式读取文件时必须编程的解析量。 为此,您的写作可以写成如下:

fwrite($myfile, $token . "\n");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM