Skip to content

Instantly share code, notes, and snippets.

@joshmfrankel
Last active September 8, 2023 12:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joshmfrankel/9e54ac68fd8682a817e2 to your computer and use it in GitHub Desktop.
Save joshmfrankel/9e54ac68fd8682a817e2 to your computer and use it in GitHub Desktop.
PHP: Fix broken html tags in string and use html entities
/**
* 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();
@Bahhous
Copy link

Bahhous commented Jun 29, 2017

$doc = new DOMDocument();
$doc->substituteEntities = false;
$content = mb_convert_encoding($sValue, 'html-entities', 'utf-8');
@$doc->loadHTML($content);
$sValue = $doc->saveHTML();

@ikidnapmyself
Copy link

thanks! it worked for me when i had to handle the html table as an value.

@Miqi180
Copy link

Miqi180 commented Sep 8, 2023

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment