When outputting text from a database, we often encounter the issue where the browser ignores new lines and indentations. Without proper processing, all your carefully written code and long paragraphs would merge into a single, unreadable line.
Solution for Paragraphs: nl2br() or <p>
If you store raw text in the database, PHP offers the nl2br() function, which converts new lines
into HTML <br> tags. In our new system, however, it is even better to wrap the text in
<p> tags during entry, as this tells the browser where the content is logically separated.
Preserving Code Formatting with <pre> and <code>
The biggest challenge is programming code. By default, the browser removes all redundant spaces. To keep the
code in "IDE format" (with all indentations), it must be output inside the <pre> tag. This
tag instructs the browser: "Display exactly as it is written in the database."
// Example of outputting from an SQL table echo "<pre><code>" . htmlspecialchars($row['content']) . "</code></pre>";
Security During Output (htmlspecialchars)
When outputting code that contains characters such as < or >, you must convert
them into HTML entities. If you fail to do so, the browser will attempt to execute the code instead of
simply displaying it.