When fetching text from a database, we often encounter the issue where the browser ignores all new lines and indentations. Without proper handling, all your carefully written code and long paragraphs would merge into a single, unreadable line.
The Solution for Paragraphs: nl2br() or <p>
If you store raw text in the database, PHP offers the nl2br() function, which converts new lines into <br> tags. However, in our new system, it is better to wrap text in <p> tags during entry, clearly defining content blocks for the browser.
Preserving Code Formatting with <pre> and <code>
The biggest challenge is source code. By default, browsers collapse multiple spaces. To keep the code in its "IDE layout" (with all indentations), it must be wrapped in the <pre> tag. This tag tells the browser: "Display this exactly as it is stored in the database."
// Example of fetching and displaying from SQL
echo "<pre><code>" . htmlspecialchars($row['content']) . "</code></pre>";
Output Security (htmlspecialchars)
When displaying code that contains characters like < or >, you must convert them into HTML entities. If you skip this, the browser will attempt to execute the code instead of just displaying it.