I've written additional snippet for including external stylesheets if somebody is interrested..
<?php
require_once __DIR__ . '/vendor/autoload.php';
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
class InlineCss
{
/**
* @var CssToInlineStyles
*/
private $cssToInlineStyles;
/**
* @var string
*/
private $html;
/**
* @var string
*/
private $css = '';
public function __construct()
{
$this->cssToInlineStyles = new CssToInlineStyles();
}
public function loadHtml()
{
$html = ob_get_clean();
if (!$html) {
throw new Exception('No Content to process. This method must be called after HTML is outputted.');
}
$this->html = $html;
}
public function includeExternalStylesheets()
{
preg_match_all('/<link[^>]+>/mi', $this->html, $matches);
$linkElements = $matches[0];
if ($linkElements) {
foreach ($linkElements as $linkElement) {
$cssContent = $this->getCssContent($linkElement);
$this->html = str_replace($linkElement, '
<style type="text/css">
' . $cssContent . '
</style>
', $this->html);
}
}
}
/**
* @param $linkElement
* @return string
*/
private function getCssContent($linkElement)
{
// load data from html element
preg_match_all("/href=['\"]([^'\"]+)['\"]/", $linkElement, $matches);
$url = $matches[1][0];
$absUrl = __DIR__ . '/../' . $url;
// this needs to be changed to search in all include paths
$cssContent = @file_get_contents($absUrl);
if (!$cssContent) {
trigger_error('Error loading stylesheet from ' . $absUrl, E_USER_NOTICE);
}
return $cssContent;
}
public function convert()
{
$this->cssToInlineStyles->setHTML($this->html);
$this->cssToInlineStyles->setCSS($this->css);
$this->cssToInlineStyles->setUseInlineStylesBlock();
$this->cssToInlineStyles->setCleanup();
$this->cssToInlineStyles->setStripOriginalStyleTags();
// output
$output = $this->cssToInlineStyles->convert();
// additional style tags cleaning
$output = str_replace('<style type="text/css"></style>', '', $output);
return $output;
}
public static function process()
{
$inlineCss = new InlineCss;
$inlineCss->loadHtml();
$inlineCss->includeExternalStylesheets();
echo $inlineCss->convert();
}
}
probably needs fixing the paths etc..