Skip to content
Tutorials Center
My learning

Topics

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
<?php
// Deprecated: prints a deprecation notice in PHP 8.2+
echo utf8_encode("caf\xE9");   // café

Try it

PHP What they do, and the deprecation notice

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.

PHP The replacements

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

PHP
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 of utf8_encode($s), and mb_convert_encoding($s, "ISO-8859-1", "UTF-8") instead of utf8_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 with mb_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, //TRANSLIT or numeric entities).
  • The root fix is to declare UTF-8 in the database connection, the Content-Type header, the HTML <meta charset> and your editor, so conversion is not needed.