Page 1 of 1

Make and display plaintext file

Posted: Wed Jun 29, 2011 7:02 pm
by giomach
I'm trying to run a php file to save some data to a plaintext file and have that file displayed in the browser.

I can save the data to the file (like this), but I don't know how to display the file in the browser immediately.

$outfile = "/tmp/output.txt";
$fp = fopen ($outfile, "w");
$lines = file($infile);
foreach($lines as $line_num => $line)
{
echo fputs ($fp, $line);
}
fclose($fp);

Now I can put in a link <a href="..."></a> to the file and click on it, but I'd rather achieve the result without clicking (and besides, the file I've just put the data in isn't addressable via such a link).

Alternatively, if I put the data straight into a page like this

<?php
$infile = "input.txt";
$lines = file($infile);
foreach($lines as $line_num => $line)
{
echo $line;
}
?>

(That's the entire php file.)

then the data comes up in the browser fine, but it's not formatted like plain text (not Courier New, no line feeds, etc.).

Adding formatting is not an answer, as the file must contain only plaintext when downloaded.

I'm obviously missing something. Can anyone tell me what it is!

Thanks.

Re: Make and display plaintext file

Posted: Wed Jun 29, 2011 9:37 pm
by twinedev

Code: Select all

<pre><tt><?php 
  $infile = "input.txt";
  $lines = file($infile);
  foreach($lines as $line_num => $line) {
    echo htmlspecialchars($line);
  }
?></tt></pre>

Re: Make and display plaintext file

Posted: Thu Jun 30, 2011 8:17 am
by giomach
Many thanks, I never would have found that.

It's almost perfect, the only thing is that, when the page is saved as text for use outside the html environment, it has those unwanted <pre> and <tt> tags in it.

Edit: That last sentence should read: when you view the page source, it has those <pre> and <tt> tags in it, which a real plaintext file being viewed in a browser doesn't have.

How is it that, when a plaintext file is shown in a browser, it is shown in Courier New with linefeeds, etc., without needing those tags? Could that mechanism be harnessed?

Thanks again.

Re: Make and display plaintext file

Posted: Thu Jun 30, 2011 2:14 pm
by twinedev
Ahh, you need it treated as a text file, just not displayed like one. Try this:

Code: Select all

<?php
header("Content-Type: plain/text"); 
readfile('inputfile.txt'); 
?>

Re: Make and display plaintext file

Posted: Sat Jul 02, 2011 5:17 pm
by giomach
That's it 100% now! Many thanks.