簡體   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