How can one ensure that line breaks are preserved while also preventing code from being executed in PHP?

To ensure that line breaks are preserved while preventing code from being executed in PHP, you can use the htmlspecialchars function to encode special characters like "<" and ">" as HTML entities. This will display the code as text on the webpage without executing it.

&lt;?php
$code = &quot;&lt;p&gt;This is a sample code snippet&lt;/p&gt;&quot;;
echo htmlspecialchars($code);
?&gt;