Home Articles HowTo Guides HowTo: Do AdSense In XHTML
HowTo: Do AdSense In XHTML PDF Print E-mail
Written by Will Daniels   
Tuesday, 29 April 2008 15:56

There are two reasons why XHTML has a problem with Google's AdSense code:

  1. It uses the javascript function Document.Write(), which XHTML can't handle because it would output new markup whilst the document is still being parsed.
  2. It creates an <iframe> element, which cannot be used with strict varieties of XHTML.

It's inconvenient, but fortunately not impossible to deal with. The solution is basically to render the ads as plain old text/html inside an object element. This does mean that you need to put your AdSense code into a separate file, referenced by the object element. An example using PHP...

Given the original AdSense script code:

<script type="text/javascript"><!--
  google_ad_client = "pub-8595518574874016";
  /* Homepage, vertical, wide */
  google_ad_slot = "5511616855";
  google_ad_width = 160;
  google_ad_height = 600;
  //-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

We replace that with:

<object width="160" height="600" data="/includes/adsense.php" type="text/html">
</object>

And create the file /includes/adsense.php as:

<?php header("Content-Type: text/html;charset=utf-8"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
  <head>
    <title>Sponsorship</title>
    <style type="text/css">
      body {margin: 0; padding:0;}
    </style>
  </head>
  <body>
    <script type="text/javascript">
      google_ad_client = "pub-8595518574874016";
      google_ad_slot = "5511616855";
      google_ad_width = 160;
      google_ad_height = 600;
    </script>
    <script type="text/javascript"
      src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
  </body>
</html>

Obviously, you have to substitute your own google_ad variables. I found this solution as an example somewhere, but I lost the link, so apologies for neglecting to give credit.

Comments
Add New RSS
+/-
Write comment
Name:
Email:
 
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
Please input the anti-spam code that you can read in the image.
Thomas     |2008-06-12 12:54:09
Hi. Thank you for this HowTo. That was it was I was searching for. It saved me
much time.

3.22 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Tuesday, 29 April 2008 21:12 )
 
 

Sponsorship

Visitors are kindly requested to give the advertisements at least a cursory glance.