| 1 |
forceutf8 |
| 2 |
========= |
| 3 |
|
| 4 |
PHP Class Encoding featuring popular \ForceUTF8\Encoding::toUTF8() function --formerly known as forceUTF8()-- that fixes mixed encoded strings. |
| 5 |
|
| 6 |
Description |
| 7 |
=========== |
| 8 |
|
| 9 |
If you apply the PHP function utf8_encode() to an already-UTF8 string it will return a garbled UTF8 string. |
| 10 |
|
| 11 |
This class addresses this issue and provides a handy static function called \ForceUTF8\Encoding::toUTF8(). |
| 12 |
|
| 13 |
You don't need to know what the encoding of your strings is. It can be Latin1 (iso 8859-1), Windows-1252 or UTF8, or the string can have a mix of them. \ForceUTF8\Encoding::toUTF8() will convert everything to UTF8. |
| 14 |
|
| 15 |
Sometimes you have to deal with services that are unreliable in terms of encoding, possibly mixing UTF8 and Latin1 in the same string. |
| 16 |
|
| 17 |
Update: |
| 18 |
|
| 19 |
I've included another function, \ForceUTF8\Encoding::fixUTF8(), which will fix the double (or multiple) encoded UTF8 string that looks garbled. |
| 20 |
|
| 21 |
Usage: |
| 22 |
====== |
| 23 |
|
| 24 |
use \ForceUTF8\Encoding; |
| 25 |
|
| 26 |
$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string); |
| 27 |
|
| 28 |
$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string); |
| 29 |
|
| 30 |
also: |
| 31 |
|
| 32 |
$utf8_string = Encoding::fixUTF8($garbled_utf8_string); |
| 33 |
|
| 34 |
Examples: |
| 35 |
|
| 36 |
use \ForceUTF8\Encoding; |
| 37 |
|
| 38 |
echo Encoding::fixUTF8("Fédération Camerounaise de Football\n"); |
| 39 |
echo Encoding::fixUTF8("Fédération Camerounaise de Football\n"); |
| 40 |
echo Encoding::fixUTF8("Fédération Camerounaise de Football\n"); |
| 41 |
echo Encoding::fixUTF8("Fédération Camerounaise de Football\n"); |
| 42 |
|
| 43 |
will output: |
| 44 |
|
| 45 |
Fédération Camerounaise de Football |
| 46 |
Fédération Camerounaise de Football |
| 47 |
Fédération Camerounaise de Football |
| 48 |
Fédération Camerounaise de Football |
| 49 |
|
| 50 |
Install via composer: |
| 51 |
===================== |
| 52 |
Edit your composer.json file to include the following: |
| 53 |
|
| 54 |
```json |
| 55 |
{ |
| 56 |
"require": { |
| 57 |
"neitanod/forceutf8": "~2.0" |
| 58 |
} |
| 59 |
} |
| 60 |
``` |
| 61 |
|
| 62 |
|