Skip to content

Instantly share code, notes, and snippets.

@kodie
Last active November 16, 2018 13:55
Show Gist options
  • Save kodie/ff41bbab9e1cd156992c97e613a1276b to your computer and use it in GitHub Desktop.
Save kodie/ff41bbab9e1cd156992c97e613a1276b to your computer and use it in GitHub Desktop.
Use PHP to modify an HTML fragment with the proper encoding
<?php
$html = '<article class="grid-item"><p>Hello World</p></article><article class="grid-item"><p>Goodbye World</p></article>';
$head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
libxml_use_internal_errors(true);
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($head . $html);
$xpath = new DOMXPath($dom);
// Loop through all article.grid-item elements and add the "invisible" class to them
$nodes = $xpath->query("//article[contains(concat(' ', normalize-space(@class), ' '), ' grid-item ')]");
foreach($nodes as $node) {
$class = $node->getAttribute('class');
$class .= ' invisible';
$node->setAttribute('class', $class);
}
$content = preg_replace('/<\/?(!doctype|html|head|meta|body)[^>]*>/im', '', $dom->saveHTML());
libxml_use_internal_errors(false);
echo $content;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment