Home / Set the content encoding type with PHP headers

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:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

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:

page info in firefox showing encoding

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.