How can special characters be properly handled when extracting PHP code from a database?

Special characters can be properly handled when extracting PHP code from a database by using the htmlspecialchars() function in PHP. This function converts special characters to their HTML entities, preventing any potential security vulnerabilities like cross-site scripting attacks.

// Retrieve PHP code from the database
$phpCode = $row['php_code'];

// Output the PHP code with special characters properly handled
echo htmlspecialchars($phpCode);