PHP – Decode multiple MIME header fields at once using iconv_mime_decode_headers()

In PHP, iconv_mime_decode_headers() function is used to decode multiple MIME header fields at once. It is an in-built function in PHP that processes encoded headers commonly found in email messages.

Syntax

iconv_mime_decode_headers($str_headers, $int_mode, $str_encoding)

Parameters

The iconv_mime_decode_headers() function accepts three different parameters − $headers, $mode and $encoding.

  • $headers − The encoded headers as a string. Contains the MIME header fields to be decoded.

  • $mode − Determines the behavior when encountering malformed MIME header fields. Can use any combination of the following bitmasks:

    • ICONV_MIME_DECODE_STRICT − Decodes headers in full conformance with standards. Disabled by default due to many broken email clients.
    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR − Ignores grammatical errors and continues processing the header.
  • $encoding − Optional parameter specifying the character set for the result. Uses iconv.internal_encoding if omitted or null.

Return Value

The iconv_mime_decode_headers() function returns an associative array containing the decoded MIME header fields on success, or False if an error occurs during decoding.

Example

The following example demonstrates decoding multiple MIME header fields ?

<?php
   $str_headers = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: xyz@example.com
Date: Mon, 21 Jun 2021 00:00:00 +0000
Message-Id: <xyz@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
     with SMTP id xyz for <xyz@example.com>;
     Mon, 21 Jun 2021 00:00:00 +0000 (UTC)
     (envelope-from example-return-0000-xyz=xyz.com@example.com)
Received: (qmail 0 invoked by uid 65534); 21 Mon 2005 00:00:00 +0000
EOF;
   
   $headers = iconv_mime_decode_headers($str_headers, 0, "UTF-8");
   print_r($headers);
?>
Array
(
    [Subject] => Prüfung Prüfung
    [To] => xyz@example.com
    [Date] => Mon, 21 Jun 2021 00:00:00 +0000
    [Message-Id] => 
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id xyz for ; Mon, 21 Jun 2021 00:00:00 +0000 (UTC) (envelope-from example-return-0000-xyz=xyz.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 21 Mon 2005 00:00:00 +0000
        )
)

Conclusion

The iconv_mime_decode_headers() function is essential for processing email headers, automatically handling encoded content and returning a structured array for easy access to individual header fields.

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

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements