Reading File with Line Breaks?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
locell
Forum Newbie
Posts: 3
Joined: Sat Oct 25, 2003 11:25 pm

Reading File with Line Breaks?

Post by locell »

I'm reading from a file that has line breaks as in spacing items like this:

Item1
ITEM2

ITEM3

But it comes out like Item1ITEM2 ITEM3

Here is the Code:

if (!$file_handle = fopen($file,"r")) { echo "Cannot open file."; }
if (!$file_contents = fread($file_handle, filesize($file))) { echo "Cannot retrieve file contents."; }
else { echo "$file_contents\r\n"; }
fclose($file_handle);

If some one could help me I'd appreciate it a LOT!!!

THANK YOU
User avatar
DuFF
Forum Contributor
Posts: 495
Joined: Tue Jun 24, 2003 7:49 pm
Location: USA

Post by DuFF »

If you are trying to output this in HTML you just need to change the \r\n to a <br>.

Instead of

Code: Select all

<?php
 else { echo "$file_contents\r\n"; } 

?>
put

Code: Select all

<?php
 else { echo "$file_contents<br>"; } 
?>
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

This will replace all of the line breaks in the file with <br> tags.

Code: Select all

<?
if (!$file_handle = fopen($file,"r")) { echo "Cannot open file."; } 

if (!$file_contents = fread($file_handle, filesize($file))) { echo "Cannot retrieve file contents."; } 
else { echo nl2br($file_contents); } 
fclose($file_handle); 
?>
Post Reply