Page 1 of 1

import text is all on one line

Posted: Sat Mar 05, 2011 5:21 pm
by jiranz
http://www.jiranz.com/test.txt
http://www.jiranz.com/test.php

The text file displays correctly in my browser but the same file displays as a single line of text when imported with php.
I have experimented with php scripts to import lists and even tried csv but the returned text always only a single line.
I seems that the php script must remove the line feeds?
How do I get the php script to display the text file correctly?

Re: import text is all on one line

Posted: Sat Mar 05, 2011 5:31 pm
by Christopher
No, the browser is displaying the text file as a text file -- using the newlines. But the PHP script is rendered as a HTML document where any whitespace is rendered as a space. You could do something like:

Code: Select all

echo str_replace("\n", '<br/>', $file_contents);

Re: import text is all on one line

Posted: Sat Mar 05, 2011 5:49 pm
by jiranz
Christopher wrote:No, the browser is displaying the text file as a text file -- using the newlines. But the PHP script is rendered as a HTML document where any whitespace is rendered as a space. You could do something like:

Code: Select all

echo str_replace("\n", '<br/>', $file_contents);
This is what is in my php file at present:

Code: Select all

<?php include("test.txt") ?>
So you are suggesting I use an alternative php script to read line by line and add in the break code?

For example where do i add it to this line by line script borrowed from the manual (which otherwise returns the same results as the above script)

Code: Select all

<?php
$handle = @fopen("test.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>
Thanks for your input :)

Re: import text is all on one line

Posted: Sat Mar 05, 2011 6:25 pm
by jiranz
I got a working script...

Code: Select all

<?php
// get contents of a file into a string
$filename = "test.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$fp = fopen('data:text/plain,'. $contents,'rb');
while ( ($line = fgets($fp)) !== false) {
  echo "$line<br>";
}
?>
Your explanation helped and I can learn from this.
Thanks.

Re: import text is all on one line

Posted: Sat Mar 05, 2011 7:57 pm
by Christopher
Well, I was assuming that your were reading the whole file.

Code: Select all

$filename = "test.txt";
$file_contents = file_get_contents($filename);
echo str_replace("\n", '<br/>', $file_contents);     // this also might be "\r"

Re: import text is all on one line

Posted: Sat Mar 05, 2011 10:04 pm
by litebearer
Or...

Code: Select all

$filename = "test.txt";
$file_contents = file_get_contents($filename);
echo nl2br($file_contents);  

Re: import text is all on one line

Posted: Sun Mar 06, 2011 2:06 am
by Christopher
Even better!