Page 1 of 1

How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 10:10 am
by eyipes
A little background, I'm making a site for a friend who sends out a daily newsletter. I'm using a simple cgi newsletter script, which I've rigged to create a "dailynews.txt" text file whenever he sends a newsletter out. On the newsletter subscription page I'd like to show the contents of the "dailynews.txt" file. This is an easy way for him to update this page daily without ever having to use ftp/html/php/etc. which he knows nothing about.

I'm using

Code: Select all

<?php include($_SERVER['DOCUMENT_ROOT'].'/mynewsfolder/dailynews.txt'); ?> 
to display the text file on the page, which works fine EXCEPT line breaks aren't displaying.

ie. a 3 paragraph message is sent, the created text file when opened shows 3 paragraphs, but on the subscription page when I'm trying to display it, the lines all flow together with no paragraph breaks.

How do I include a text file in a page so the line breaks are displayed?

Thanks so much for your help,
Diane

Re: How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 10:41 am
by buckit
I believe you are looking for nl2br() http://us.php.net/manual/en/function.nl2br.php

Re: How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 10:52 am
by McInfo
Option 1: (Most Practical) Use file_get_contents() to load the text from the file into a string and pass that string to nl2br() to convert the newlines into HTML line breaks.

Option 2: (Silly) Wrap the include in output buffering functions and capture the output before sending it to the browser. Use nl2br() on the captured string to convert the newlines to HTML line breaks.

Option 3: (Not Aesthetic) Put the include within <pre> tags so the newlines render natively.

Option 4: (Unpredictable) Teach your friend a little HTML.

Edit: Fixed numbering mistake

Re: How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 10:56 am
by Eran
The <pre> option is the best in my opinion, since it will also preserve white-space. You can use CSS to dress it up a little so it will look good

Re: How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 11:04 am
by McInfo
If long lines are expected, I would avoid <pre>.

Edit: Never mind... You can use the white-space CSS property to make the text wrap in a <pre>.

Re: How to display line breaks in txt file with php include?

Posted: Fri Sep 17, 2010 1:15 pm
by eyipes
Thank you very much, a css formatted pre tag worked perfectly!

Funny that, I've heard of pre tags but never needed it before or even knew what it did. So now I've learned new stuff today. It's always the simple stuff that stumps me.

Oh, and LOL at Option 4 - since I'm hosting his pages for him on my server alongside my own sites, it's exactly that "unpredictable" factor I'm trying to avoid :D

Thanks again!