How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

manycheese picture manycheese · Nov 25, 2010 · Viewed 1M times · Source

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.

Answer

Gumbo picture Gumbo · Nov 25, 2010

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.