PHP – Convert a string to a requested character encoding using iconv()

In PHP, the iconv() function is used to convert a string from one character encoding to another. It performs character set conversion on the string from a source encoding to a target encoding, making it essential for handling multilingual text and ensuring proper character display across different systems.

Syntax

string iconv(string $from_encoding, string $to_encoding, string $string)

Parameters

The iconv() function accepts three parameters:

  • $from_encoding − The input charset (source encoding)

  • $to_encoding − The output charset (target encoding). You can append //TRANSLIT or //IGNORE for special handling

  • $string − The string to be converted

Return Value

Returns the converted string on success, or FALSE on failure.

Example 1: Basic Character Encoding Conversion

<?php
    // Convert UTF-8 to ISO-8859-1
    $text = "Hello World with special chars: café";
    
    echo 'Original: ' . $text . PHP_EOL;
    echo 'Converted: ' . iconv("UTF-8", "ISO-8859-1", $text) . PHP_EOL;
?>
Original: Hello World with special chars: café
Converted: Hello World with special chars: café

Example 2: Using TRANSLIT and IGNORE Options

<?php
    // Text with characters that might not exist in target encoding
    $string = "Currency symbols: ? ¥ £";
    
    echo 'Original: ' . $string . PHP_EOL;
    echo 'TRANSLIT: ' . iconv("UTF-8", "ASCII//TRANSLIT", $string) . PHP_EOL;
    echo 'IGNORE: ' . iconv("UTF-8", "ASCII//IGNORE", $string) . PHP_EOL;
?>
Original: Currency symbols: ? ¥ £
TRANSLIT: Currency symbols: EUR Y GBP
IGNORE: Currency symbols:   

Key Points

  • //TRANSLIT − Transliterates unsupported characters to similar ones

  • //IGNORE − Silently discards unsupported characters

  • Without these options, conversion fails if unsupported characters are encountered

Conclusion

The iconv() function is essential for character encoding conversion in PHP. Use //TRANSLIT for approximate character replacement or //IGNORE to skip unsupported characters when converting between different encodings.

Updated on: 2026-03-15T09:56:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements