【问题标题】:Php fopen delete each readed line while readingphp fopen 在阅读时删除每个已阅读的行
【发布时间】:2016-04-11 13:19:09
【问题描述】:

我有密码

$handle = fopen(getcwd() . "/emails.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        SendEmails($line,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
        $line.delete; // here i need to delete each readed line
    }
    fclose($handle);
} else {
    echo "error opening the file.";
} 

阅读时如何删除每行已读?

【问题讨论】:

  • 因为执行有问题并且 fopen 开始重复行,我认为当浏览器超时时会发生这种情况。因此,如果有空字符串 fopen 读取它们,但我只需要归档字符串

标签: php


【解决方案1】:

试试这个

$handle = fopen(getcwd() . "/emails.txt", "r");
$readedlines="";
if ($handle) {
while (($line = fgets($handle)) !== false) {
SendEmails($line,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);
   $readedlines=$readedlines.$line;
fclose($handle);
$newFileContent=str_replace($readedlines,"",file_get_contents($filename));
$handle=fopen($filename, "w");
fwrite($handle,$newFileContent);
fclose($handle);
} else {
echo "error opening the file.";
 } 

我的意思是将所有读取的行连接成一个字符串并替换整个文件内容字符串。 希望有帮助

【讨论】:

  • 好吧,这意味着您想在 while loop 运行时删除行?。
  • OP 这么说,但似乎你的回答对他来说已经足够了。
  • 它适用于 OP 描述的某些情况 - 但它既不是所描述问题的一般解决方案,也不是优雅的解决方案。
  • 可能是用两个handler并行运行可以解决问题。表示 $handle1=fopen(filename."r");和 $handle2=fopen("文件名","w");并在一个while循环中使用它们
【解决方案2】:
// Get file contents
$contents = file_get_contents('/emails.txt');

// Explode to get contents in an array
$rows = explode("\n", $contents);

file_put_contents('/emails.txt', "");

// Loop through all rows in emails.txt
foreach ($rows as $row) {
    // If sending the email fails, add row to $notSent
    if (false === SendEmails($row, $strSubject, $strMessage, $txtFormName, $txtFormEmail, $fname, $ftype,$tmp_path)) {
        $contents = file_get_contents('/emails.txt');
        $contents .= $row."\n";
        file_put_contents('/emails.txt', $contents);
    }
}

【讨论】:

  • 再一次 - 如果脚本在 foreach 中中断 - 不会将任何内容写入您的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
相关资源
最近更新 更多