php教程

iconv_mime_decode

(PHP 5, PHP 7)

iconv_mime_decode解码一个MIME头字段

说明

iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : string

解码一个MIME头字段.

参数

encoded_header

编码头,是一个字符串.

mode

模式决定了当iconv_mime_decode()遇到一个不规则的 MIME头字段时,对这个事件作出的行为.你可以指定以下位掩码的任意组合.

可以在iconv_mime_decode()中使用的位掩码
常量 描述
1 ICONV_MIME_DECODE_STRICT 如果使用该位掩码,传入的头字段将会完全一致的按照» RFC2047的标准定义被解码. 这个选项默认是禁用的,因为有很多零散的邮件用户代理商不遵守标准规范并且不生成正确的MIME头.
2 ICONV_MIME_DECODE_CONTINUE_ON_ERROR 如果使用该位掩码,iconv_mime_decode_headers() 将会试图忽略任何错误语法,并继续处理传入的头字段.

charset

可选的字符集参数,用指定的字符集表示结果.如果省略, iconv.internal_encoding 将会被默认使用.

返回值

如果解码成功,返回一个被解码的MIME字段, 如果在解码过程中出现一个错误,将返回FALSE .

范例

Example #1 iconv_mime_decode()实例

<?php
//返回结果: "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       
0"ISO-8859-1");
?>

参见

User Contributed Notes

Dirk Becker 26-Jul-2013 09:46
While creating a new webmailer, I had to coop with a lot of mails and only half of them were correct encoded!
Often the text is tagged as ISO but in real its UTF :/

After trying a lot of solutions and combination a found a way which seems to work for all our mails. Maybe its usefull to someone else too.

<?php

   
function mime_encode($data)
    {
       
$resp = imap_utf8(trim($data));

        if(
preg_match("/=\?/", $resp))
           
$resp = iconv_mime_decode($data, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "ISO-8859-15");

        if(
json_encode($resp) == 'null')
           
$resp = utf8_encode($resp);

        return
$resp;
    }

?>
koronci at aol dot com 19-Dec-2012 11:24
A simple and working solution for latin encoding supports Slovak, Czech, Russian ect.
<?php iconv("utf-8", "windows-1250", $SomeWeirdText); ?>

specially for those who strugle with imap_mime_header_decode
dido dot sevilla at gmail dot com 09-Mar-2005 08:00
In PHP versions that have imap_mime_decode built in, it's possible to emulate the operation of this function:

<?php
function iconv_mime_decode($str, $mode=0, $charset="UTF-8")
{
   
$data = imap_mime_header_decode($str);
    if (
count($data) > 0) {
     
// because iconv doesn't like the 'default' for charset
     
$charset = ($data[0]->charset == 'default') ? 'ASCII' : $data[0]->charset;
      return(
iconv($charset, $charset, $data[0]->text));
    }
    return(
"");
 }
?>

I've only tried to use this code snippet to decode ISO-2022-JP messages to UTF-8, but I see no reason why it shouldn't work in other cases.

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788