Last active
May 23, 2022 06:47
-
-
Save yookoala/1bf4037c0dfcc6ef824e7327308958cc to your computer and use it in GitHub Desktop.
A short script to extract the head and body contents from an HTML file to reformat it
This file contains 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
<?php | |
/** | |
* Extract HTML children of a give tag name from a given document. | |
* | |
* @param \DOMDocument $doc The DOM document to extract from. | |
* @param string $tagName The tag name for extraction (e.g. 'head', 'body') | |
* | |
* @return \DOMDocument An DOMElement containing all child elements from the tag specified in $dom. | |
*/ | |
function extractChildrenFrom(\DOMDocument $doc, string $tagName): \DOMDocument { | |
$collection = new \DOMDocument; | |
$tags = $doc->getElementsByTagName($tagName); | |
$count = $tags->count(); | |
for ($i = 0; $i < $count; $i++) { | |
$tag = $tags->item($i); | |
foreach ($tag->childNodes as $element) { | |
if ($element instanceof \DOMText) { | |
continue; // do not import DOMText | |
} | |
if (($newElement = $collection->importNode($element, true)) === false) { | |
throw new \Exception('Unable to import element.'); | |
} | |
$collection->appendChild($newElement); | |
} | |
} | |
return $collection; | |
} | |
// extract HTML sections from the file | |
// Note: this is very slow, need to cache the result | |
$file = __DIR__ . '/rentcaculator.html'; | |
$dom = new \DOMDocument(); | |
$dom->loadHTMLFile($file); | |
$head = extractChildrenFrom($dom, 'head'); | |
$body = extractChildrenFrom($dom, 'body'); | |
?> | |
<html> | |
<head> | |
<?=html_entity_decode($head->saveHTML())?> | |
<style> | |
/** some css */ | |
@media (max-width: 960px) { | |
.fluid-row { | |
display: grid; | |
grid-template-columns: 150px calc(100vw - 150px); | |
grid-template-rows: 50% 50%; | |
grid-template-areas: | |
"left-sidebar top-chart" | |
"left-sidebar bottom-chart"; | |
} | |
.fluid-row div { | |
display: block; | |
float: none; | |
width: 100%; | |
} | |
.fluid-row div:nth-child(1) { | |
grid-area: left-sidebar; | |
} | |
.fluid-row div:nth-child(2) { | |
grid-area: top-chart; | |
} | |
.fluid-row div:nth-child(3) { | |
grid-area: bottom-chart; | |
} | |
} | |
</style> | |
</head> | |
<body> | |
<?=html_entity_decode($body->saveHTML())?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment