What are some best practices for handling special characters, such as umlauts, when retrieving data from a database in PHP?

Special characters, such as umlauts, can cause encoding issues when retrieving data from a database in PHP. To handle these characters properly, you should ensure that your database connection is set to use the correct character set, such as UTF-8. Additionally, you can use PHP functions like utf8_encode() or utf8_decode() to properly encode or decode special characters.

// Set the character set for the database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'username', 'password');

// Fetch data from the database
$stmt = $pdo->query('SELECT * FROM mytable');
while ($row = $stmt->fetch()) {
    // Decode special characters using utf8_decode()
    $name = utf8_decode($row['name']);
    echo $name . '<br>';
}