PHP – Set the current setting for character encoding conversion using iconv_set_encoding() function

In PHP, the iconv_set_encoding() function is used to set the current character encoding conversion. It is an inbuilt function in PHP that changes the value of the internal configuration variable specified by type to encoding.

Syntax

string iconv_set_encoding(string $type, string $encoding)

Parameters

iconv_set_encoding() takes two parameters −

  • $type − The $type parameter can be input_encoding, output_encoding or internal_encoding.

  • $encoding − The $encoding parameter is used for the character set.

Return Values

iconv_set_encoding() returns TRUE on success and FALSE on failure.

Example

Here's how to set different encoding types using iconv_set_encoding() function ?

<?php
    // Set internal encoding to UTF-8
    $result = iconv_set_encoding("internal_encoding", "UTF-8");
    
    // Display current encodings after setting
    $encodings = iconv_get_encoding();
    var_dump($encodings);
    
    // Set output encoding to ISO-8859-1
    iconv_set_encoding("output_encoding", "ISO-8859-1");
    
    // Display encodings again
    echo "\nAfter changing output encoding:<br>";
    $updated_encodings = iconv_get_encoding();
    var_dump($updated_encodings);
?>

Output

array(3) {
  ["input_encoding"]=>
  string(5) "UTF-8"
  ["output_encoding"]=>
  string(5) "UTF-8"
  ["internal_encoding"]=>
  string(5) "UTF-8"
}

After changing output encoding:
array(3) {
  ["input_encoding"]=>
  string(5) "UTF-8"
  ["output_encoding"]=>
  string(10) "ISO-8859-1"
  ["internal_encoding"]=>
  string(5) "UTF-8"
}

Conclusion

The iconv_set_encoding() function provides fine-grained control over character encoding settings in PHP. Use it to configure input, output, or internal encoding based on your application's requirements.

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

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements