Skip to content
PHP Logo

How can PHP urlencode be used to ensure UTF8 compatibility?

When using PHP's urlencode function with UTF-8 characters, it may not encode them correctly, leading to compatibility issues. To ensure UTF-8 compatibility, you can first convert the string to UTF-8 using mb_convert_encoding and then urlencode it. This will properly encode UTF-8 characters and prevent any encoding errors.

php
$string = "UTF-8 string with special characters like ü and ñ";
$encoded_string = urlencode(mb_convert_encoding($string, "UTF-8"));
echo $encoded_string;