1

I am trying to write to some txt files using SplFileObject's fwrite method and getting below error message.

Fatal error: Maximum execution time of 30 seconds exceeded in /Users/oliverwilliams/Desktop/olliephp/directory.php on line 9.

Line 9 is while (!$textfile->eof()) { from the following code

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

I am new to PHP. How get rid of that error?

This is the code I was emulating, from David Powers Lynda course. His code does work.

$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");
    }
    }
Ollie_W
  • 337
  • 1
  • 5
  • 13
  • The whole `while` code is not correct. – Peter VARGA Mar 05 '16 at 13:08
  • Ok...What is wrong with it? – Ollie_W Mar 05 '16 at 13:28
  • instead of looping to the end of file why not just using the `a` mode which does it for you? – Gal Sisso Mar 05 '16 at 13:47
  • You call `next` on a `file` object which cannot resolve the `next` method. `next` is valid for the directory iterator: http://php.net/manual/en/filesystemiterator.next.php - the whole logic is wrong. Check the example in the link I sent you. Apart from this `Gal` is right... – Peter VARGA Mar 05 '16 at 13:51
  • Hi Gal, thanks for the advice. Removing the while loop and changing 'r+' to 'a' does work and write to the files and is certainly an easier way of doing things. I was following along with the code of David Power's SPL course on Lynda.com. He normally seems to know what he is talking about but I don't understand why this code worked for him and not for me :( – Ollie_W Mar 05 '16 at 13:55

0 Answers0