Set HTTP header to UTF-8 using PHP

0 votes
asked Nov 25, 2010 by manycheese

I have several PHP pages echoing out various things into HTML pages with the following code.

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

However, when I validate using the W3C validator it comes up with:

The character encoding specified in the HTTP header (iso-8859-1) is different from the value in the element (utf-8).

I am quite new to PHP, and I was wondering if I could and should change the header for the PHP files to match the HTML files.

6 Answers

0 votes
answered Nov 25, 2010 by gumbo

Use header to modify the HTTP header:

header('Content-Type: text/html; charset=utf-8');

Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent. See the manual page of header for more information.

0 votes
answered Nov 25, 2010 by kingcrunch

First make sure the PHP files themselves are UTF-8 encoded.

The meta tag is ignored by some browser. If you only use ASCII-characters, it doesn't matter anyway.

http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

header('Content-Type: text/html; charset=utf-8');
0 votes
answered Nov 25, 2010 by edododo

This is a problem with your web server sending out a HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

0 votes
answered Nov 18, 2014 by jason-ooo

You can also use shorter way:

<?php header('Content-Type: charset=utf-8'); ?>

See RFC 2616 its valid to specify only charset.

0 votes
answered Nov 18, 2014 by unchien-andalou

For correct implementation, you need to change a series of things.

Database.(immediately after the connection):

mysql_query("SET NAMES utf8");
//Meta tag HTML.(probably its already set): 
meta charset="utf-8"
header php.(before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset(for each row):
utf8_unicode_ci
0 votes
answered Sep 15, 2017 by nikl

PHP send headers automatically if set up internal encoding

ini_set('default_charset', 'utf-8');
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...