Last active
December 16, 2015 23:49
-
-
Save whymarrh/5516427 to your computer and use it in GitHub Desktop.
In-lines CSS, JavaScript, and images.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
define(SUCCESS, 0); | |
define(ERROR, 1); | |
if (count($argv) != 2) { | |
printf("usage: %s <filename>\n", basename($argv[0])); | |
exit(ERROR); | |
} | |
$filename = $argv[1]; | |
if (!file_exists($filename)) { | |
printf("Please choose a file that exists.\n"); | |
exit(ERROR); | |
} | |
$dir = dirname($filename) ? dirname($filename) . DIRECTORY_SEPARATOR : ""; | |
$document = new DOMDocument("1.0", "UTF-8"); | |
$document->loadHTMLFile($filename); | |
// CSS | |
$links = $document->getElementsByTagName("link"); | |
$stylesheets = array(); | |
for ($i = 0; $i < $links->length; $i++) { | |
$link = $links->item($i); | |
if ($link->getAttribute("rel") == "stylesheet") { | |
$stylesheets[$i] = $link; | |
} | |
} | |
$css = ""; | |
foreach ($stylesheets as $stylesheet) { | |
$css .= file_get_contents($dir . $stylesheet->getAttribute("href")); | |
$stylesheet->parentNode->removeChild($stylesheet); | |
} | |
if ($css) { | |
$style = $document->createElement("style", $css); | |
$head = $document->getElementsByTagName("head")->item(0); | |
$head->appendChild($style); | |
} | |
// JavaScript | |
$scripts = $document->getElementsByTagName("script"); | |
foreach ($scripts as $script) { | |
$src = $script->getAttribute("src"); | |
if (!filter_var($src, FILTER_VALIDATE_URL)) { | |
$src = $dir . $src; | |
} | |
$script->removeAttribute("src"); | |
$script->appendChild($document->createTextNode(file_get_contents($src))); | |
} | |
// Images | |
$imgs = $document->getElementsByTagName("img"); | |
foreach ($imgs as $img) { | |
$filename = $img->getAttribute("src"); | |
if (!filter_var($filename, FILTER_VALIDATE_URL)) { | |
$filename = $dir . $filename; | |
} | |
$mime = mime_content_type($filename); | |
$data = base64_encode(file_get_contents($filename)); | |
$img->setAttribute("src", "data:$mime;base64,$data"); | |
} | |
$stripped = preg_replace('#>\s+<#s', '><', $document->saveHTML()); | |
printf("%s\n", $stripped); | |
exit(SUCCESS); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment