Use iconv() when you need to converts text between named character encodings in a PHP application. The examples below show the actual operation and its limitations.
What Is iconv() in PHP?
Converts text between named character encodings. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
iconv(string $from_encoding, string $to_encoding, string $string): string|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo iconv("UTF-8","ISO-8859-1","Cafe");
Output:
Cafe
Example 2: Different Input or Behavior
<?php
echo iconv("UTF-8","UTF-8","Sample");
Output:
Sample
Practical Example: Applying the Function
<?php
$source = "Résumé"; $converted = iconv("UTF-8","ISO-8859-1",$source); echo iconv("ISO-8859-1","UTF-8",$converted);
Output:
Résumé
Important Behavior and Edge Cases
Characters not representable in the target encoding can trigger errors or data loss; do not silently discard them.
Comparison With Related Functions
| Approach | Difference |
|---|---|
iconv() | Converts text between named character encodings. |
| Related operation | mb_convert_encoding() offers another encoding conversion interface when mbstring is installed. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Characters not representable in the target encoding can trigger errors or data loss; do not silently discard them. |
| Confusing this function with a related operation | mb_convert_encoding() offers another encoding conversion interface when mbstring is installed. |
Key Takeaways
- Converts text between named character encodings.
- Characters not representable in the target encoding can trigger errors or data loss; do not silently discard them.
- mb_convert_encoding() offers another encoding conversion interface when mbstring is installed.
Use iconv() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.