简体   繁体   中英

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?

  • 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

You will need to set the header before you output any html.

Try to set the header before your first HTML tag. EG:

<?php header('Content-type: text/html; charset=utf-8'); ?>
<!DOCTYPE HTML>
<head>
    <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>

After a lot of searching I came across the following question. In the database connection I had to specify that I wanted the UTF-8 charset. I did it the following way:

$db = new PDO('mysql:host=localhost;dbname=NAME;charset=utf8', 'USERNAME', 'PASSWORD');

It must have been a server update from the host that caused the problem, since I haven't been affected by the problem before now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM