How can PHP developers ensure that line breaks in text are preserved when outputting to HTML?

When outputting text from PHP to HTML, developers can ensure that line breaks are preserved by using the PHP function nl2br(). This function converts newline characters (\n) into HTML line breaks (<br>). By applying nl2br() to the text before outputting it to the HTML page, developers can maintain the original line breaks in the displayed text.

$text = &quot;This is a sample text with\nline breaks.&quot;;
echo nl2br($text);