When should special characters and umlauts be replaced in PHP code, such as before writing to a database or only when needed for specific outputs like RSS feeds or GET parameters?

Special characters and umlauts should be replaced in PHP code before writing to a database to prevent SQL injection attacks and ensure data integrity. Additionally, they should be replaced when needed for specific outputs like RSS feeds or GET parameters to ensure compatibility with different systems and prevent encoding issues.

// Replace special characters and umlauts before writing to a database
$clean_data = mysqli_real_escape_string($connection, $raw_data);

// Replace special characters and umlauts for specific outputs like RSS feeds or GET parameters
$clean_output = htmlspecialchars($raw_output, ENT_QUOTES, 'UTF-8');