Simon Simon - 7 months ago 121
PHP Question

Alternative to mb_convert_encoding with HTML-ENTITIES charset

I have the following code:

mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8');

I need to have an alternative code which does exactly the same but does not use any mb_* functions (the mb extension is not available on some environments).

I thought that

utf8_decode(htmlentities($string, ENT_COMPAT, 'utf-8'));

should do exactly the same, but unfortunately it does not.


I played around a bit, and find this very interesting. It seems like the second part also runs "htmlspecialchars". Must be some bug in mb_convert_encoding, as htmlentities is not run correctly.

If you run htmlspecialchars_decode over the result, you get exactly the same as if you would use mb_convert_encoding.

The code:

$string = 'Test:!"$%&/()=ÖÄÜöäü<<';
echo mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8')."\n\n";
echo htmlspecialchars_decode(utf8_decode(htmlentities($string, ENT_COMPAT, 'utf-8', false)));

Here a demo of the code above:

And here a demo without htmlspecialchars_decode, to show your problem: