一個解碼字串的好方法是使用 mb_list_encodings(),但它有兩個問題
有時候,標頭中的字元集是大寫,而 mb_list_encodings() 中的字元集是小寫,有時候,字元集不在 mb_list_encodings() 清單中。
<?php
function upperListEncode() { $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)) { case 'UTF-8': $texte.= $tabChaine[$i]->text; break;
case 'DEFAULT': $texte.= $tabChaine[$i]->text; break;
default: if (in_array(strtoupper($tabChaine[$i]->charset),upperListEncode())) {$texte.= mb_convert_encoding($tabChaine[$i]->text,'UTF-8',$tabChaine[$i]->charset);}
else { $ret = iconv($tabChaine[$i]->charset, "UTF-8", $tabChaine[$i]->text);
if (!$ret) $texte.=$tabChaine[$i]->text; else $texte.=$ret;
}
break;
}
}
return $texte;
}
?>