What are the potential issues with using nl2br() to handle line breaks in PHP text output?

Using nl2br() to handle line breaks in PHP text output can potentially introduce security vulnerabilities such as Cross Site Scripting (XSS) attacks if the input is not properly sanitized. To solve this issue, it is recommended to use htmlspecialchars() in conjunction with nl2br() to escape any HTML characters before converting line breaks to <br> tags.

$text = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;\nThis is a new line.&quot;;
$safe_text = nl2br(htmlspecialchars($text));
echo $safe_text;