Home  >  Article  >  Backend Development  >  How to change string to UTF8 in PHP?

How to change string to UTF8 in PHP?

Guanhui
GuanhuiOriginal
2020-06-15 16:32:563436browse

How to change string to UTF8 in PHP?

How to change a string to UTF8 in PHP?

In PHP, you can use the "iconv()" function to change the string to UTF8. The function of this function is to convert the string according to the required character encoding. Its syntax is "iconv(in, out,str)", when using it, set in to the encoding of the string, set out to UTF8, and set str to the string to be converted.

Conversion example

$str = "123456789";

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

Usage example

<?php
//some German
$utf8_sentence = &#39;Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz&#39;;

//UK
setlocale(LC_ALL, &#39;en_GB&#39;);

//transliterate
$trans_sentence = iconv(&#39;UTF-8&#39;, &#39;ASCII//TRANSLIT&#39;, $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, &#39;de_DE&#39;);

$trans_sentence = iconv(&#39;UTF-8&#39;, &#39;ASCII//TRANSLIT&#39;, $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;
?>

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of How to change string to UTF8 in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn