What are the best practices for handling output from PHP functions like highlight_string() to ensure proper display within HTML elements?
When using PHP functions like highlight_string() to format code for display within HTML elements, it is important to properly encode the output to ensure it is displayed correctly. This can be done by using htmlentities() or htmlspecialchars() functions to escape special characters in the output before inserting it into the HTML.
<?php
$code = "<?php echo 'Hello, world!'; ?>";
$highlighted_code = highlight_string($code, true);
$escaped_code = htmlspecialchars($highlighted_code);
echo "<pre>$escaped_code</pre>";
?>