How can PHP variables with line breaks be properly formatted for HTML output?

When PHP variables with line breaks are echoed directly into HTML output, the line breaks may not be displayed as intended. To properly format PHP variables with line breaks for HTML output, you can use the nl2br() function in PHP. This function converts newlines in a string to HTML line breaks (<br> tags), allowing the line breaks to be displayed correctly in the HTML output.

&lt;?php
// PHP variable with line breaks
$text = &quot;Hello\nWorld&quot;;

// Format the variable for HTML output
$formatted_text = nl2br($text);

// Output the formatted text
echo $formatted_text;
?&gt;