ba haran
ba haran

Reputation: 15

Open the text file in the browser

I use the following command to display text files in the browser:

echo file_get_contents($filename);

But this command displays the lines of the message continuously. I want to display the lines of the article, such as a separate text file. What is your solution?

Upvotes: 1

Views: 433

Answers (2)

eMerzh
eMerzh

Reputation: 625

only using file_get_contents will correctly output your file as text in your browser, the issue is that your browser will interpret it as html. In html multiple whitespaces are "merged" so your file is displayed as continous list.

You have to possibilities here :

  • saying to your browser that you will give him text (adding a header to the response)
header('Content-Type:text/plain');
echo file_get_contents($filename);
  • converting the text to correctly be displayed in html
$text = file_get_contents($filename);
echo "<pre>".htmlEntities($text)."</pre>";

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can use nl2br to insert HTML line breaks before all newlines in a string.

nl2br ( string $string [, bool $is_xhtml = TRUE ] ) : string

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Usage:

$content = file_get_contents($filename);
echo nl2br($content);

Upvotes: 4

Related Questions