PHP Reference · String Functions
PHP utf8_encode() and utf8_decode() functions
Reference for PHP utf8_encode() and utf8_decode(), deprecated since PHP 8.2: what they really do (Latin-1 only), their surprises and the replacements.
utf8_encode() converts a string from ISO-8859-1 (Latin-1) to UTF-8, and utf8_decode() converts UTF-8 back to Latin-1. Despite their names, they handle only that one pair of encodings. They were deprecated in PHP 8.2, so calling them raises a deprecation notice, and they will be removed in a future major version.
The names have misled many developers into running them on text that is already UTF-8, which produces garbled output (mojibake, such as é in place of é). utf8_decode() is also lossy: every character outside Latin-1 is silently replaced with ?.
<?php // Deprecated: prints a deprecation notice in PHP 8.2+ echo utf8_encode("caf\xE9"); // café
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
utf8_encode(string $string): string utf8_decode(string $string): string
| Name | Description |
|---|---|
$string |
For utf8_encode(), Latin-1 text. For utf8_decode(), UTF-8 text. |
Return value: the converted string. Neither function reports invalid input; utf8_decode() writes ? for characters it cannot convert.
Usage notes
- Deprecated in 8.2. Replace them:
mb_convert_encoding($s, "UTF-8", "ISO-8859-1")instead ofutf8_encode($s), andmb_convert_encoding($s, "ISO-8859-1", "UTF-8")instead ofutf8_decode($s).iconv()also works. - They only know Latin-1. Windows-1252 text (very common in old Windows data) has extra characters such as
€and curly quotes in the byte range Latin-1 treats as controls. Convert from"Windows-1252"when you know that is the source. - Never run
utf8_encode()on UTF-8. Check withmb_check_encoding()first, or fix the source of the data instead of repairing it afterwards. utf8_decode()is lossy. If you need to send data to a system that only accepts a legacy encoding, handle unrepresentable characters on purpose (error,//TRANSLITor numeric entities).- The root fix is to declare UTF-8 in the database connection, the
Content-Typeheader, the HTML<meta charset>and your editor, so conversion is not needed.