By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

XHTML and Mime Types

How to apply the correct Mime Type to your XHTML Documents.

Created: 2013-06-28 00:49

If you are using XHTML then you should be serving it with the application/xhtml+xml mime type, there are several reasons for this, which is covered further in this article.

Mime types are used to describe the content of the file which was requested on the server.

The PHP Solution

The header function of PHP

In the top of your PHP Script, simply have the below:

header(" Content-type: application/xhtml+xml");

Browser Support

Some browsers however doesn't support XHTML, so for those we might want to consider serving our XHTML 1.0 page with text/html instead, later versions of XHTML must be served with the application/xhtml+xml mime type. I recommend that you don't do this, for a few reasons which i cover later in this article.

Anyway, to check if a user agent supports the mime type, we simply include an if statement, see below:

if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
  header("Content-type: application/xhtml+xml");
else {
  header("Content-type: text/html");

Using the Correct Mime Type

Using the wrong mime type may result in a number of errors, truly html compatible xhtml is hard to get. For instance, a xhtml document served as text/html will be rendered as tag soup. Empty elements which where closed, will render the page invalid as html 4.01.

Layout Problems

Users serving their pages as text/html often design their pages with html4 behaviour in mind, and when they finally decide to use the correct mime type, the rendering of their page would be likely to break. Not to mention that some of these pages wouldn't even render with the correct mime-type, since their xhtml markup itself was invalid.

Style and Script Elements

Style and script elements needs extra strings included, if they are to be used in both HTML4 and XHTML, this reminds more of a workaround then a solution. This is because script and style tags are #PCDATA blocks in XHTML, rather then #CDATA. So if you need to embed CSS in both HTML and XHTML, then it would require something like:

<style type="text/css"><!--/*--><![CDATA[/*><!--*/

/* Code Goes Here */


Similar methods are used when it comes to script elements, see below:

<script type="text/javascript"><!--//--><![CDATA[//><!--

<!-- Code Goes Here -->


So there is a lot to take into consideration when serving XHTML with the incorrect mime type for older user agent.

I would recommend simply not to do it, and then tell your users to upgrade their browser. Users of Windows 9x would then be adviced to shift to opera, since microsoft are unlikely to update older versions of IE. Shifting to opera has other benefits, such as improved support for web standards.