Search code examples
phphtmlutf-8character-encoding

Charset UTF-8 and php header() not working


I am having some problems with the charset on my website. I can't get the UTF-8 charset to work and I get � instead of Å. Yes, I have searched around the web for answers and I've already used the following code:

<!DOCTYPE HTML>
<head>
    <?php header('Content-type: text/html; charset=utf-8'); ?>
    <meta http-equiv="Content-Type" content="text/html" charset=utf-8" />
    <title><?php echo $db_title; ?></title>
</head>
<body>
    Some content with letters æøå
</body>
</html>

The database uses latin1_swedish_ci.

Any idea what it could be?


Solution

    • Set the PHP header tag before any output to the browser (as pointed out by JJ Cantillon)

    • While PHP and HTML use the correct UTF-8, it is worth noting that MySQL uses a reduced version of UTF-8 and so when selecting the Collation of the database tables/fields the "utf8_general_ci" (and similar) are not full character sets and so your characters you want to display will not be stored correctly.

    What you need to do is to ensure MySQL uses the complete UTF-8 character set by selecting

    Collation = 'utf8mb4'

    Also, when you are connecting your script to the database you need to specify the same (utf8mb4) character set for PHP/MySQL communication - so set something like (in as far as MySQLi or PDO etc.)

    new PDO('mysql:host=localhost;charset=utf8mb4')  
    

    or for MySQLi read up on http://php.net/manual/en/mysqli.set-charset.php

    If you store data in the SQL as utf8mb4 but only transfer the data using standard MySQL-utf8 (3bytes rather than 4bytes) then the character sets will be screwed up in transport.

    Reading: https://stackoverflow.com/a/16893103/3536236