If we know that the current encoding is ASCII, the 'iconv' function can be used to convert ASCII to UTF-8. The original string can be passed as a parameter to the iconv function to encode it to UTF-8.
Example
<?php $str = "ábrêcWtë"; echo 'Original :', ("$str"), PHP_EOL; echo 'Plain :', iconv("UTF-8", "ISO-8859-1", $str), PHP_EOL; ?>
A string with special characters is assigned to ‘str’ variable. This is passed to the ‘iconv’ function, with the encoding that it currently is in, and the encoding to which it needs to be converted to.
Output
This will produce the following output −
Original :ábrêcWtë Plain :�br�cWt�
Another method is to detect the encoding and then converting it to an appropriate encoding −
Example
$string = "ábrêcWtë"; print(mb_detect_encoding ($string)); $string = mb_convert_encoding($string, "UTF-8"); print(mb_detect_encoding ($string));
A string value with special characters is assigned to ‘string; variable. This is passed to the ‘mb_convert_encoding’ function that converts it to the target encoding.
Output
This will produce the following output −
UTF-8UTF-8