PHP – Compose a MIME header field using iconv_mime_encode() function

In PHP, the iconv_mime_encode() function is used to compose MIME header fields. This built-in function creates properly encoded headers that can contain non-ASCII characters, commonly used in email headers and HTTP responses.

Syntax

string iconv_mime_encode(string $field_name, string $field_value, array $options=[])

The function returns a string representing a valid MIME header field ?

Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FFr?= Entwerfen von einer MIME kopfzeile

Note − In the above example, Subject is the field name, and the portion beginning with "=ISO-8859-1?..." is the encoded field value.

Parameters

The function accepts three parameters −

  • $field_name − The name of the header field (e.g., "Subject", "From").

  • $field_value − The value to be encoded in the header field.

  • $options − An optional associative array containing configuration items to control encoding behavior.

Configuration Options

Item Type Description Default Value Example
scheme string Encoding method: "B" (base64) or "Q" (quoted-printable) B Q
input-charset string Character set of input field_name and field_value iconv.internal_charset ISO-8859-1
output-charset string Character set for MIME header composition input-charset value UTF-8
line-length integer Maximum length of header lines 76 996
line-break-chars string End-of-line sequence for line folding \r

Example 1 − Using Quoted-Printable Encoding

<?php
   // Configuration options
   $options = array(
      "input-charset" => "ISO-8859-2",
      "output-charset" => "UTF-8",
      "line-length" => 76,
      "line-break-chars" => "<br>",
      "scheme" => "Q"  // Quoted-printable encoding
   );

   // Encode header with special characters
   echo iconv_mime_encode("Subject", "Prüfung Prüfung", $options);
?>
Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?=

Example 2 − Using Base64 Encoding

<?php
   // Configuration for base64 encoding
   $options = array(
      "input-charset" => "ISO-8859-1",
      "output-charset" => "UTF-8",
      "line-length" => 76,
      "line-break-chars" => "<br>",
      "scheme" => "B"  // Base64 encoding
   );

   // Encode header with accented characters
   echo iconv_mime_encode("Subject", "Preços Olà.txt", $options);
?>
Subject: =?UTF-8?B?UHJlw6dvcyBPbMOgLnR4dA==?=

Conclusion

The iconv_mime_encode() function is essential for creating properly encoded MIME headers that contain non-ASCII characters. Use "Q" encoding for readable text with few special characters and "B" encoding for binary data or heavily encoded content.

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

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements