PHP – 使用 iconv_mime_decode_headers() 一次性解码多个 MIME 标头字段

phpserver side programmingprogramming更新于 2025/7/22 8:37:17

在 PHP 中,iconv_mime_decode_headers() 函数用于一次性解码多个 MIME 标头字段。它是 PHP 的内置函数。

语法

iconv_mime_decode_headers($str_headers, $int_mode, $str_encoding)

参数

iconv_mime_decode_headers() 函数接受三个不同的参数− $headers、$mode 和 $encoding。

  • $headers − $header 参数用于编码标头。它是一个字符串类型参数。

  • $mode − $mode 参数决定了 iconv_mime_decode_headers() 遇到变形的 MIME 标头字段时的行为。我们可以使用以下位掩码的任意组合。

  • iconv_mime_decode_headers() 可接受的位掩码列表

    • ICONV_MIME_DECODE_STRICT
    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR
    • ICONV_MIME_DECODE_STRICT - 如果设置了 iconv_mime_decode_strict,则给定的标头将完全符合解码要求,但此选项默认处于禁用状态,因为许多损坏的邮件用户代理不符合要求,无法生成正确的 MIME 标头。
    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR - 如果如果设置了 iconv_mime_decode_continue_on_error() 参数,它会尝试忽略任何语法错误并继续处理给定的标头。
  • $encoding − 编码是一个可选参数,用于指定表示结果的字符集。如果省略或为 null,则将使用 iconv.internal_encoding。

返回值

如果成功,iconv_mime_decode_headers() 函数将返回一个关联数组,其中包含由标头指定的整个 MIME 标头字段集合;如果解码过程中出现任何错误,则返回 False。

示例 1

<pre>
   <?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, "ISO-8859-1");
      print_r($headers);
   ?>
</pre>

输出

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
      )
)

相关文章