I am currently reading and displaying the entire contents of a text file using the following code:

$html_get = file('content.txt');
foreach ($html_get as $html_num => $html_text) {
echo $html_text;
}

I would like, however, to have the code read the contents of the text file up to a certain line of code eg <!-- StopReadingHere -->. And a similar code to start reading from a line of code in a similar way.

Anyone know how best to do this?

Thanks,
Martin

Hi martinkorner,

Try using strpos along with fread. Aside from that, you could read in a line of the file at a time:

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
$token = '<!-- STOP HERE -->';
if ($handle) {
    $superbuffer = array();
    while (!feof($handle)) {
        $buffer = fgets($handle);
        if($buffer == $token) {
          echo 'Stopping...';
          // Jump out of this loop
        } else {
          $superbuffer[] = $buffer;
        }
    }
    fclose($handle);
    echo join('<br>',$superbuffer);
}
?>

Of course, I didn't try the code above, but in theory, that would do what you want it too. You can also specify a length for fgets to read so that it only reads the first 39 characters or whatever.

I hope this is somewhat close to what you are looking for.

Great question by the way!

Thanks chrelad,

I tried this, and tried reading each line individually, but the 'stop' term oddly never gets found (I have checked I'm searching for the correct term - which is on it's own line).
I wonder if this is because the $buffer holds a space after the line from the text file. I have tried searching for the 'stop' term with a space after it, but still no luck.

Any ideas?

Speak Soon,
Martin

Hi martinkorner,

You may have better luck using regular expressions to find the search term instead of using '==' syntax. There are flags which tell preg_match/ereg_match to ignore whitespaces and the like... You could try that and see what you come up with. That's where I'd start anyway :)

Hi martinkorner,

You may have better luck using regular expressions to find the search term instead of using '==' syntax. There are flags which tell preg_match/ereg_match to ignore whitespaces and the like... You could try that and see what you come up with. That's where I'd start anyway :)

or try with explode

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.