How can PHP encode line breaks for HTML output, such as using <br> or \n?

To encode line breaks for HTML output in PHP, you can use the nl2br() function. This function converts newlines (\n) in a string to HTML line breaks (<br>). Simply pass the string containing line breaks to nl2br() before outputting it to the HTML page.

$text_with_line_breaks = &quot;This is a text\nwith line breaks.&quot;;
$text_with_html_line_breaks = nl2br($text_with_line_breaks);
echo $text_with_html_line_breaks;