Created
April 8, 2015 00:06
-
-
Save stronk7/47b9c896677982113c70 to your computer and use it in GitHub Desktop.
Fix broken HTML using DOM hidden superpowers...
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 | |
$brokenhtml = '<p>this is broken</p>because i want to </div></div></div><script><script type="text/javascript"><!--'; | |
echo fixhtmlplz($brokenhtml) . "\n\n"; | |
$brokenhtml = '<b>because <i>I can leave <p>everything <div> unclosed | |
using many <span> lines and <ul> more yet <li> lists | |
<li> more and | |
<li> more'; | |
echo fixhtmlplz($brokenhtml) . "\n\n"; | |
function fixhtmlplz($brokenhtml) { | |
$preparehtml = '<?xml version="1.0" encoding="UTF-8"?><prepared>' . $brokenhtml . '</prepared>'; | |
$doc = new DomDocument(); | |
libxml_use_internal_errors(true); | |
$doc->loadHTML($preparehtml); | |
libxml_clear_errors(); | |
$temphtml = $doc->saveHTML($doc->getElementsByTagName('prepared')->item(0)); | |
$fixedhtml = preg_replace('#<prepared>(.*)</prepared>#s', '$1', $temphtml); | |
return $fixedhtml; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment