2

我正在编写我的第一个 PHP 代码,我想显示一些电子邮件主题。

header('content-type: text/html; charset=utf-8');
...
$header = imap_headerinfo($imap, $i);
$raw_body = imap_body($imap, $i);
$subject = utf8_encode($header->subject);

echo $subject;
echo "<br>";
...

但是对于主题“ää üü öö ß”,输出如下所示:

=?ISO-8859-1?B?5OQg/Pwg9vYg3w==?=

问候

解决方案:

我在网上发现了一个非常有用的功能(http://php.net/manual/de/function.imap-mime-header-decode.php),它有两个小语法错误,但经过一些返工后它工作得很好我。

最后解决方案看起来像这样:

//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8',     
$targetCharset='utf-8',$fallbackCharset='iso-8859-1') {
$encodings=mb_list_lowerencodings();
$inputCharset=strtolower($inputCharset);
$targetCharset=strtolower($targetCharset);
$fallbackCharset=strtolower($fallbackCharset);

$decodedStr='';
$mimeStrs=imap_mime_header_decode($mimeStr);
for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
  $mimeStr=$mimeStrs[$i];
  $mimeStr->charset=strtolower($mimeStr->charset);
if (($mimeStr == 'default' && $inputCharset == $targetCharset)
  || $mimeStr->charset == $targetCharset) {
  $decodedStr.=$mimStr->text;
} else {
  $decodedStr.=mb_convert_encoding(
    $mimeStr->text, $targetCharset,
    (in_array($mimeStr->charset, $encodings) ?
      $mimeStr->charset : $fallbackCharset)

  );
}
} return $decodedStr;
}

...

$header = imap_headerinfo($imap, $i);
$raw_body = imap_body($imap, $i);
$sub = decodeMimeString($header->subject);
echo $sub;
...

我想指出,这两个函数是作者@http: //php.net/manual/de/function.imap-mime-header-decode.php创建的,我刚刚删除了两个语法错误。

谢谢你的回复

4

2 回答 2

1

这是一种常见的邮件格式,称为“引用打印”。所有非 ascii 字符都被编码。(见http://en.wikipedia.org/wiki/Quoted-printable

该字符串由

=?<encoding>?Q?<string>?=

<encoding>描述编码。这里:ISO8859-1

<string>是字符串本身

请使用 imap_mime_header_decode() 解码字符串(在使用 utf8_encode() 之前)!

于 2012-07-21T18:52:51.337 回答
0

如果 Muhammad 的回答还不够,您可以使用iconv 函数来更改字符串的编码

iconv("ISO-8859-1", "UTF-8", $your_string);
于 2012-07-21T18:48:05.433 回答