What potential pitfalls can arise when trying to output HTML code from PHP variables in a file?
When outputting HTML code from PHP variables in a file, potential pitfalls include accidentally injecting malicious code through user input or failing to properly escape special characters, leading to syntax errors or broken HTML rendering. To mitigate these risks, always sanitize user input and escape characters using functions like htmlspecialchars() before echoing variables into the HTML file.
<?php
// Example PHP code snippet to output sanitized HTML code from a PHP variable in a file
// Sample PHP variable containing HTML code
$html = "<h1>Hello, world!</h1>";
// Sanitize the HTML code before outputting
$sanitized_html = htmlspecialchars($html);
// Output the sanitized HTML code in a file
$file = fopen("output.html", "w");
fwrite($file, $sanitized_html);
fclose($file);
?>