Basic Usage
The function can be expressed into a simple syntax as shown:
The function will take the string, the encoding format to convert to, and the encoding from which to convert. PHP will default to the internal encoding if the value of from_encoding is not provided. You can also pass an array. PHP will recursively convert all the string values in the provided array.
Upon success, the function will return the encoded string or array of strings. A return value of false should be returned if the process fails.
Example Usage
Using examples, let us illustrate how to use the PHP mb_convert_encoding() method.
Example 1: Internal Encoding
The first example shows you how to use the mb_convert_encoding() method from an internal encoding. This is done by setting the value of the from_convert parameter to null, as shown.
In the example above, we create a simple PHP script that converts a specified string from internal encoding to “Unicode Transformation Format – 16-bit Little Endian.”
Before executing the code above, you may require to install the PHP mbstring package.
On Ubuntu and Debian-based distros, run the command:
On CentOS/REHL, enter the command:
Example 2: From UTF-8 to EUC-KR*
The example below shows you how to use the mb_convert_encoding() function to convert a string from UTF-8 to EUC-KR.
$str = "Hello";
$convert = mb_convert_encoding($str, "UTF-8", "EUC-KR");
print_r($convert);
?>
Example 3: Auto-Detect Encoding
The PHP mb_convert_encoding() function also allows you to specify a set of encoding formats, and it will automatically detect from which to convert. The example code is as shown:
$str = "";
$convert = mb_convert_encoding($str, "UTF-8, UTF-7, UTF-16LE, JIS", "EUC-KR");
print_r($convert);
?>
In the example code above, the function will detect the specified encoding such as ash UTF-8, UTF-7, UTF-16LE, and JIS. It will then convert the value to the EUC-KR encoding format.
Example 4: Convert Array
We can also pass an array to the mb_convert_encoding() method. Consider the example below:
$str = array("Hello", "world");
$convert = mb_convert_encoding($str, "UTF-8", "JIS");
print_r($convert);
?>
The code above will recursively convert each string in the array from UTF-8 to JIS and return an array of the converted values.
Conclusion
In this guide, you learned how to use the PHP mb_convert_encoding method. This gives you the ability to perform encoding conversion in your PHP functions.
Thank you for reading!