mb_string Encoding Error

Warning: mb_convert_encoding(): Unable to detect character encoding

Quick Answer

The multibyte string function cannot detect the encoding of the input. Specify the source encoding explicitly instead of relying on auto-detection.

Why This Happens

PHP's mb_string functions can attempt to auto-detect encoding, but this is unreliable. When detection fails, the function may return false or produce garbled output. Always specify both source and target encodings explicitly for reliable results.

The Problem

$utf8 = mb_convert_encoding($data, 'UTF-8'); // Source encoding not specified

The Fix

$utf8 = mb_convert_encoding($data, 'UTF-8', 'ISO-8859-1');
// Or detect first with a strict list:
$encoding = mb_detect_encoding($data, ['UTF-8', 'ISO-8859-1', 'ASCII'], true);
if ($encoding === false) {
    throw new RuntimeException('Unable to detect encoding');
}
$utf8 = mb_convert_encoding($data, 'UTF-8', $encoding);

Step-by-Step Fix

  1. 1

    Determine the source encoding

    Find out what encoding the source data uses. Check the database charset, file encoding, or API response headers.

  2. 2

    Specify encoding explicitly

    Always pass the source encoding as the third parameter to mb_convert_encoding instead of relying on auto-detection.

  3. 3

    Validate after conversion

    Use mb_check_encoding() to verify the converted string is valid in the target encoding.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free