Last active
November 16, 2018 13:55
-
-
Save kodie/ff41bbab9e1cd156992c97e613a1276b to your computer and use it in GitHub Desktop.
Use PHP to modify an HTML fragment with the proper encoding
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 | |
$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