If you apply utf8_encode()
to an already UTF-8 string, it will return garbled UTF-8 output.
I made a function that addresses all this issues. It´s called Encoding::toUTF8()
.
You don't need to know what the encoding of your strings is. It can be Latin1 (ISO 8859-1), Windows-1252 or UTF-8, or the string can have a mix of them. Encoding::toUTF8()
will convert everything to UTF-8.
I did it because a service was giving me a feed of data all messed up, mixing UTF-8 and Latin1 in the same string.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);
Download:
https://github.com/neitanod/forceutf8
I've included another function, Encoding::fixUFT8()
, which will fix every UTF-8 string that looks garbled.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::fixUTF8($garbled_utf8_string);
Examples:
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
will output:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
I've transformed the function (forceUTF8
) into a family of static functions on a class called Encoding
. The new function is Encoding::toUTF8()
.
If you are 100% sure $message contain ISO-8859-1 you can use utf8_encode as David says. Otherwise use mb_detect_encoding and mb_convert_encoding on $message.
Also take note that
$mail -> charSet = "UTF-8";
Should be replaced by:
$mail->CharSet = 'UTF-8';
And placed after the instantiation of the class (after the new
). The properties are case sensitive! See the PHPMailer doc fot the list & exact spelling.
Also the default encoding of PHPMailer is 8bit
which can be problematic with UTF-8 data. To fix this you can do:
$mail->Encoding = 'base64';
Take note that 'quoted-printable'
would probably work too in these cases (and maybe even 'binary'
). For more details you can read RFC1341 - Content-Transfer-Encoding Header Field.
Best Answer
My phpmailer installation uses 8bit by default. No need to change anything.
However if I want "quoted printable", I just add the following code:
One thing to remember: When you want quoted-printable you do not need to pre-encode your text, Phpmailer will encode it for you.
Maybe you can try without defining the encoding and see if it works.