Convert ASCII TO UTF-8 Encoding in PHP?

In PHP, you can convert ASCII to UTF-8 encoding using built-in functions like iconv() and mb_convert_encoding(). Both functions provide different approaches for character encoding conversion.

Using iconv() Function

The iconv() function converts strings between different character encodings. It requires specifying the source and target encodings −

<?php
    $str = "Hello World";
    echo 'Original ASCII: ' . $str . PHP_EOL;
    echo 'UTF-8 Encoded: ' . iconv("ASCII", "UTF-8", $str) . PHP_EOL;
?>
Original ASCII: Hello World
UTF-8 Encoded: Hello World

Example with Special Characters

<?php
    // Sample string with extended ASCII characters
    $str = "caf" . chr(233); // café in extended ASCII
    echo 'Original: ' . $str . PHP_EOL;
    echo 'To UTF-8: ' . iconv("ISO-8859-1", "UTF-8", $str) . PHP_EOL;
?>
Original: café
To UTF-8: café

Using mb_convert_encoding() Function

The mb_convert_encoding() function provides automatic encoding detection and conversion −

<?php
    $string = "Hello ASCII World";
    echo 'Original encoding: ' . mb_detect_encoding($string) . PHP_EOL;
    
    $converted = mb_convert_encoding($string, "UTF-8");
    echo 'After conversion: ' . mb_detect_encoding($converted) . PHP_EOL;
    echo 'Converted string: ' . $converted . PHP_EOL;
?>
Original encoding: ASCII
After conversion: UTF-8
Converted string: Hello ASCII World

Comparison

Function Auto-Detection Error Handling Best For
iconv() No Strict Known source encoding
mb_convert_encoding() Yes Flexible Unknown source encoding

Conclusion

Use iconv() when you know the source encoding, and mb_convert_encoding() for automatic detection. Both functions effectively convert ASCII to UTF-8 encoding in PHP.

Updated on: 2026-03-15T08:42:22+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements