Last active
September 8, 2023 12:22
-
-
Save joshmfrankel/9e54ac68fd8682a817e2 to your computer and use it in GitHub Desktop.
PHP: Fix broken html tags in string and use html entities
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
/** | |
* Fix for broken html tags inside strings for php. | |
* | |
* By using passing the html through DOMDocument and converting the html | |
* entities we are left with beautiful well formatted code. Huzzah! | |
* | |
* "Nothing is ever easy" -Zedd, Wizards First Rule | |
* | |
* @var DOMDocument | |
*/ | |
$doc = new DOMDocument(); | |
$doc->substituteEntities = false; | |
$content = mb_convert_encoding($sValue, 'html-entities', 'utf-8'); | |
$doc->loadHTML($content); | |
$sValue = $doc->saveHTML(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works beautifully! Extremely useful for parsing and fixing malformed html from user input (e.g. from a WYSIWYG editor) before inserting it into e.g. an html email body. Thanks!