PHP 8.5.0 Released!

imap_mime_header_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mime_header_decodeMIME ヘッダ要素をデコードする

説明

imap_mime_header_decode(string $string): array|false

非 ASCII テキストの MIME メッセージヘッダエクステンションをデコードします (» RFC2047 を参照ください)。

パラメータ

string

MIME テキスト。

戻り値

デコードされた要素は、オブジェクトの配列で返されます。 各オブジェクトは、二つのプロパティ charsettext を有しています。

要素がエンコードされていない場合、言い替えるとプレーンな US-ASCII の場合は この要素の charset プロパティは default に設定されます。

この関数は、失敗した時に false を返します。

例1 imap_mime_header_decode() の例

<?php
$text
= "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <[email protected]>";

$elements = imap_mime_header_decode($text);
for (
$i=0; $i<count($elements); $i++) {
echo
"Charset: {$elements[$i]->charset}\n";
echo
"Text: {$elements[$i]->text}\n\n";
}
?>

上の例の出力は以下となります。

Charset: ISO-8859-1
Text: Keld Jørn Simonsen

Charset: default
Text:  <[email protected]>

上の例には二つの要素があります。最初の要素は ISO-8859-1、 2 番目の要素はプレーンな US-ASCII で事前にエンコードされています。

参考

  • imap_utf8() - MIME エンコードされたテキストを UTF-8 に変換する

add a note

User Contributed Notes 1 note

up
9
Anonymous
12 years ago
A nice way to decode strings is to use the mb_list_encodings(), but I had two problems with it: 
sometimes, the charset is uppercase in the header an lowercase in mb_list_encodings() and sometimes, the charset is not in the mb_list_encodings() list.

<?php
function upperListEncode() { //convert mb_list_encodings() to uppercase
    $encodes=mb_list_encodings();
    foreach ($encodes as $encode) $tencode[]=strtoupper($encode);
    return $tencode;
    }

function decode($string) {
    $tabChaine=imap_mime_header_decode($string);
    $texte='';
    for ($i=0; $i<count($tabChaine); $i++) {
        
        switch (strtoupper($tabChaine[$i]->charset)) { //convert charset to uppercase
            case 'UTF-8': $texte.= $tabChaine[$i]->text; //utf8 is ok
                break;
            case 'DEFAULT': $texte.= $tabChaine[$i]->text; //no convert
                break;
            default: if (in_array(strtoupper($tabChaine[$i]->charset),upperListEncode())) //found in mb_list_encodings()
                        {$texte.= mb_convert_encoding($tabChaine[$i]->text,'UTF-8',$tabChaine[$i]->charset);}
                     else { //try to convert with iconv()
                          $ret = iconv($tabChaine[$i]->charset, "UTF-8", $tabChaine[$i]->text);    
                          if (!$ret) $texte.=$tabChaine[$i]->text;  //an error occurs (unknown charset) 
                          else $texte.=$ret;
                        }                    
                break;
            }
        }
        
    return $texte;    
    }
?>
To Top