亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 php 將 echo 的所有變量結果保存到 txt 文件中?

如何使用 php 將 echo 的所有變量結果保存到 txt 文件中?

PHP
侃侃無極 2023-09-15 09:38:59
我編寫了一個生成隨機令牌的 php 腳本,我想將這些令牌輸出到 .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文件的方法嗎?
查看完整描述

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 標簽。


查看完整回答
反對 回復 2023-09-15
?
德瑪西亞99

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");


查看完整回答
反對 回復 2023-09-15
  • 2 回答
  • 0 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號