PHP – How to decode a MIME header field using iconv_mime_decode() function?

In PHP, iconv_mime_decode() function is used to decode MIME-encoded header fields commonly found in email messages. This function handles encoded text that uses formats like Base64 or Quoted-Printable encoding within MIME headers.

Syntax

string iconv_mime_decode(string $string, int $mode = 0, string $encoding = null)

Parameters

The iconv_mime_decode() function accepts three parameters −

  • $string − The MIME-encoded header string to decode (required).

  • $mode − Optional parameter that controls decoding behavior. Available constants:

    • ICONV_MIME_DECODE_STRICT − Enforces strict RFC compliance (disabled by default due to broken mail clients)

    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR − Continues processing despite grammatical errors

  • $encoding − Optional character set for the result. Uses iconv.internal_encoding if omitted.

Return Value

Returns the decoded string on success, or false on failure.

Example

Here's how to decode a MIME-encoded header containing non-ASCII characters −

<?php
// Decode a MIME-encoded subject header
$encoded = "Subject: =?UTF-8?B?VGVzdCDDqW1haWwgd2l0aCDDqcOgIMOp?=";
$decoded = iconv_mime_decode($encoded, 0, "UTF-8");
echo $decoded . "
"; // Decode with error handling $malformed = "Subject: =?UTF-8?B?SW52YWxpZA==?= broken"; $result = iconv_mime_decode($malformed, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "UTF-8"); echo $result; ?>
Subject: Test émail with éà é
Subject: Invalid broken

Common Use Cases

  • Decoding email subject lines with international characters

  • Processing email headers from various mail clients

  • Converting MIME-encoded text in web applications

Conclusion

The iconv_mime_decode() function is essential for handling MIME-encoded email headers, especially when dealing with international characters. Use the continue-on-error mode for better compatibility with malformed headers from various email clients.

Updated on: 2026-03-15T09:55:31+05:30

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements