Integrating Styled Google Calendar with Your Website

In 2012 I started to wrote this article. In the end I quit writing it. I encountered it today again and I decided to finish it. Here it is.

My brother needed a calendar that shows his availability to his clients for his website. So, I know that already, marvelous Google Calendar provides embedding calendar in your website with iframe. But you couldn’t change its design (color, icons etc.). This is a bad thing for websites without white background color. It looks like an alien attached to your website.

I googled it a bit and I found this article: Integrating Google Calendar with your website. There is a PHP code in the article that it isn’t correct. But it inspired me. I took its idea and code and I reworked on it. Here is the live result: http://taneryilmaz.pro/#schedule 

taneryilmaz.pro - Schedule

<?php
$your_google_calendar="[YOUR_CALENDAR_EMBED_URL]";

$url= parse_url($your_google_calendar);
$google_domain = $url['scheme'].'://'.$url['host'].dirname($url['path']).'/';

// Load and parse Google's raw calendar
$dom = new DOMDocument;
$dom->loadHTMLfile($your_google_calendar);

// Create a link to a new CSS file called schedule.min.css
$element = $dom->createElement('link');
$element->setAttribute('type', 'text/css');
$element->setAttribute('rel', 'stylesheet');
$element->setAttribute('href', '/css/schedule.min.css');

// Change Google's JS file to use absolute URLs
$scripts = $dom->getElementsByTagName('script');

foreach ($scripts as $script) {
  $js_src = $script->getAttribute('src');
  
  if ($js_src) {
    $parsed_js = parse_url($js_src, PHP_URL_HOST);
    if (!$parsed_js) {
      $script->setAttribute('src', $google_domain . $js_src);      
    }
  }
}

 // Append this link at the end of the element
$head = $dom->getElementsByTagName('head')->item(0);
$head->appendChild($element);

// Remove old stylesheet
$oldcss = $dom->documentElement;
$link = $oldcss->getElementsByTagName('link')->item(0);
$head->removeChild($link);

// Export the HTML
echo $dom->saveHTML();
?>

Save this as calendar.php and after change the $your_google_calendar variable with your calendars URL. Now, you can change the style of calendar from schedule.min.css file. After that, you can embed it to your web page like this:

<iframe style="border-width: 0;" src="/calendar.php" width="560" height="400" frameborder="0" scrolling="no"></iframe>

You need to store schedule.min.css on your server to achieve this. Feel free to ask if you get any trouble.