2 回答

TA貢獻1777條經驗 獲得超10個贊
在我看來,最有效的方法就是每件事都做足夠的次數。這意味著我們必須循環并生成代碼,但我們只需要寫入文件一次,與 echo 相同。
$code = "start value";
while ($code != "e3b0"){
$arr[] = $code = bin2hex(random_bytes(2));
}
echo $str = implode("\n", $arr);
file_put_contents("output.txt", $str);
這是所有事情都執行足夠的次數,并且是更優化的代碼。
但是,如果您在瀏覽器中運行它,那么它不會將它們輸出到屏幕上的單獨行上,而只會輸出到 txt 文件中。但如果你打開源代碼,它將位于不同的行上。
那是因為我在 implode 中沒有使用 br 標簽。

TA貢獻1770條經驗 獲得超3個贊
在原始OP問題中從未詢問過效率。正在編輯這篇文章以提高效率,即無需重新打開和關閉文件。
您的使用w+將始終將文件指針放置在文件的開頭并在進程中截斷文件。因此,您總是會得到最后寫入的值。
從php.net開始fopen w+:
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+") or 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
修正:
在循環內重復打開和關閉文件是不必要的(也不高效)。a+由于您正在追加,因此您可以在循環開始之前打開它一次;并在循環結束后關閉它。
就寫入文件的標記之間的分隔符而言,回車符(換行符)是一個不錯的選擇。通過這種方式,您可以減少以編程方式讀取文件時必須進行的解析量。為此,您的寫入可以寫成如下:
fwrite($myfile, $token . "\n");
- 2 回答
- 0 關注
- 199 瀏覽
添加回答
舉報