1

我正在尝试使用 SplFileObject 的 fwrite 方法写入一些 txt 文件并收到以下错误消息。

致命错误:在第 9 行的 /Users/oliverwilliams/Desktop/olliephp/directory.php 中超过了 30 秒的最大执行时间。

第 9 行while (!$textfile->eof()) {来自以下代码

$dir = new FilesystemIterator('garbagedirectory');
foreach ($dir as $file) {
    if ($file->getExtension() === 'txt') {
        $textfile = $file -> openFile('r+');
        while (!$textfile->eof()) {
            $textfile -> next();
        }
        $textfile->fwrite("This line was added dynamically");
    }
}

我是 PHP 新手。如何摆脱这个错误?

这是我正在模仿的代码,来自 David Powers Lynda 课程。他的代码确实有效。

$docs = new FilesystemIterator('garbagedirectory');
foreach ($docs as $doc) {
if ($doc->getExtension() == 'txt') {
    $textfile = $doc->openFile('r+');
    $textfile->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD
    | SplFileObject::DROP_NEW_LINE);
    echo '<h2>' . $textfile->getFilename() . '</h2>';
    foreach ($textfile as $line) {
        echo "$line<br>";
    }
    $textfile->seek(3);
    echo '<br>';
    echo 'This is the fourth line: ' . $textfile->current();
    while(!$textfile->eof()) {
        $textfile->next();
    }
    $textfile->fwrite("\r\n\r\nThis line was added dynamically");
    }
    }
4

0 回答 0