Set the content encoding type with PHP headers

Although you can set content type in the HTML <head> section of a web page the web server can also send the content type as one of its headers, and it can cause unexpected consequences when rendering a page in a browser. This post looks at how to set the content encoding type header with PHP.

I was recently setting up a new version of a website and due to some issues with rendering special characters in the content we needed to make sure the document was served as iso-8859-1. The HTML head section looked like this:

Comparing the new version of the site with the old version, which was more or less the same (although the old version was not in standards mode) the particular characters rendering incorrectly on the new version but correctly in the old version.

Firefox has a useful function to see what the web server is telling the browser. Right-click the page and select the "View Page Info" option. This will show you something like this:

Although I'd specified the content type to be iso-8859-1 it was sill showing as UTF-8 so the page wasn't rendering correctly. The site uses PHP as the scripting language so a nice simple solution was to set the content-type with PHP like so:

header('Content-Type: text/html; charset=iso-8859-1');

This now fixed the issue with the web server setting the content type as UTF-8 and it was now showing as iso-8859-1 and the page rendered correctly.