PHP如何把字串改成UTF8?

2020-07-16 10:06:29

PHP如何把字串改成UTF8?

在PHP中可以使用「iconv()」函數把字串改成UTF8,該函數作用是將字串按要求的字元編碼來轉換,其語法為「iconv(in,out,str)」,使用時將in設定為字串的編碼,out設定為UTF8,str設定為要轉換的字串即可。

轉化範例

$str = "123456789";

$str = iconv('ASCII', 'UTF8', $str);

使用範例

<?php
//some German
$utf8_sentence = 'Wei?, Goldmann, G?bel, Weiss, G?the, Goethe und G?tz';

//UK
setlocale(LC_ALL, 'en_GB');

//transliterate
$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]
//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL;

//Germany
setlocale(LC_ALL, 'de_DE');

$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]
//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ? = ae, ? = oe and ü = ue)
echo $trans_sentence . PHP_EOL;

?>
<?php
$tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
$chain = "";
foreach ($tab as $i)
    {
        foreach ($tab as $j)
        {
            $chain .= " $i$j ".iconv($i, $j, "$my_string");
        }
    }

echo $chain;
?>
以上就是PHP如何把字串改成UTF8?的詳細內容,更多請關注TW511.COM其它相關文章!