Skip to content
PHP Logo

How can the use of <pre> tags maintain text formatting in PHP when reading from a text file?

When reading text from a file in PHP, the formatting such as line breaks and spaces may not be preserved when displaying the content on a webpage. To maintain the text formatting, you can use the <pre> HTML tag which preserves whitespace and line breaks. Simply wrap the content from the file in <pre> tags before displaying it on the webpage.

php
<?php
$file = 'sample.txt';
$content = file_get_contents($file);
echo '<pre>' . $content . '</pre>';
?>