问题
I'm using PHP imap to read emails out of an inbox. It extracts some information from headers. One of the headers looks like this:
X-My-Custom-Header: =?UTF-8?B?RXVnZW4gQmFiacSH?=
The original value of that encoded string is Eugen Babić.
When I try to decode that string using PHP, I can't get it quite right, the ć always comes back messed up.
I've tried imap_utf8, imap_mime_header_decode and a bunch of others I can't quite recall. They either don't return anything at all, or they mess up the ć as I mentioned before.
What is the correct way to decode this?
回答1:
Here's what you're doing wrong: You're HTML (as generated by the PHP) is not UTF-8 encoded. So even though it's returning the accented c, the page isn't displaying it correctly.
To fix it, add this in your <head>
tag:
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
回答2:
imap_utf8
and imap_mime_header_decode
work just fine; there's also iconv_mime_decode
:
php > echo imap_utf8('X-My-Custom-Header: =?UTF-8?B?RXVnZW4gQmFiacSH?='), "\n";
X-My-Custom-Header: Eugen Babić
php > list($k,$v) = imap_mime_header_decode('X-My-Custom-Header: =?UTF-8?B?RXVnZW4gQmFiacSH?=');
php > echo $v->text, "\n";
Eugen Babić
php > echo iconv_mime_decode('X-My-Custom-Header: =?UTF-8?B?RXVnZW4gQmFiacSH?=', 0, "utf8"), "\n";
X-My-Custom-Header: Eugen Babić
It seems that imap_utf8
returns its output in NFD, so that the accent over the c may appear out of place in some settings.
回答3:
The function mb_decode_mimeheader() solved the problem
"fromName" => (isset($fromInfo->personal))
? mb_decode_mimeheader( $fromInfo->personal) : "",
来源:https://stackoverflow.com/questions/17184199/decoding-utf-8-encoded-header