Convert UTF-8 Characters to &-Encoded HTML Entities

Nowadays, most websites and web servers should serve UTF-8 characters. But, some still don’t. So, when you’re provide a web service that is to be consumed by a third party and your content appears crappy because you’re UTF-8 characters became garbled somewhere along the way, you can convert them to &-encoded HTML entities by using PHP’s mb_convert_encoded() function. For example, you can pass your entire HTML source code for a page through the function and then pass it again through PHP’s htmlspecialchars_decode() function to convert special HTML characters (<, >, etc) back to special characters so the page renders correctly in a browser.

// convert special characters to HTML entities
$htmlsourcecode = mb_convert_encoding($htmlsourcecode, "HTML-ENTITIES", "UTF-8");

// revert HTML characters back from HTML entities
$htmlsourcecode = htmlspecialchars_decode($htmlsourcecode);