Search code examples
phpencodingcharacter-encodinggmailimap

PHP imap weird encoding characters


I'm using PHP to get my gmail email messages. It gives me email titles which look like this:

=?ISO-8859-13?Q?Darba_s=E2k=F0ana_ar_Gmail?= 

It should actually look like this (those are Latvian characters normally available in utf8):

Darba sākšana ar Gmail

I tried:

utf8_encode(quoted_printable_decode(
   "=?ISO-8859-13?Q?Darba_s=E2k=F0ana_ar_Gmail?="
));

And it gives me the following, which is not correct:

=?ISO-8859-13?Q?Darba_sâkðana_ar_Gmail? 

How do I get this - Darba sākšana ar Gmail


Solution

  • You must use imap_mime_header_decode function:

    $text = "=?ISO-8859-13?Q?Darba_s=E2k=F0ana_ar_Gmail?=";
    
    $elements = imap_mime_header_decode($text);
    foreach ($elements as $element) {
        echo "Charset: $element->charset\n";
        echo "Text: $element->text\n\n";
    }
    

    And you can use iconv function to convert:

    iconv($element->charset, 'utf-8', $element->text);