- iconv
- Список параметров
- Возвращаемые значения
- Примеры
- iconv
- Список параметров
- Возвращаемые значения
- Примеры
- How to resolve the error «iconv(): Wrong charset, conversion from UTF7-IMAP to UTF-8//IGNORE is not allowed» on PHP and Laravel
- Causes of the Error iconv(): Wrong charset, conversion from ‘UTF7-IMAP’ to ‘UTF-8//IGNORE’ is not allowed
- Solutions to Fix the Error iconv(): Wrong charset, conversion from ‘UTF7-IMAP’ to ‘UTF-8//IGNORE’ is not allowed
- Install or enable the iconv php extension
- Use an alternative function for charset conversion:
- Installing iconv and mbstring php extensions on Windows, Linux Ubuntu and Mint, MacOs
- Installing iconv and mbstring on Linux Debian based
- Installing iconv and mbstring on CentOs
- Installing iconv and mbstring on MacOs
- Installing iconv and mbstring on Windows XAMPP
- Installing iconv and mbstring on Windows WampServer
- Final considerations
iconv
Преобразует набор символов строки string из кодировки from_encoding в to_encoding .
Список параметров
Требуемая на выходе кодировка.
Если добавить к to_encoding строку //TRANSLIT , включается режим транслитерации. Это значит, что в случае, если символ не может быть представлен в требуемой кодировке, он будет заменен на один или несколько наиболее близких по внешнему виду символов. Если добавить строку //IGNORE , то символы, которые не могут быть представлены в требуемой кодировке, будут удалены. В случае отсутствия вышеуказанных параметров будет сгенерирована ошибка уровня E_NOTICE , а функция вернет false .
Как будет работат //TRANSLIT и будет ли вообще, зависит от системной реализации iconv() ( ICONV_IMPL ). Известны некоторые реализации, которые просто игнорируют //TRANSLIT , так что конвертация для символов некорректных для to_encoding скорее всего закончится ошибкой.
Строка, которую необходимо преобразовать.
Возвращаемые значения
Возвращает преобразованную строку или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования iconv()
echo ‘Исходная строка : ‘ , $text , PHP_EOL ;
echo ‘С добавлением TRANSLIT : ‘ , iconv ( «UTF-8» , «ISO-8859-1//TRANSLIT» , $text ), PHP_EOL ;
echo ‘С добавлением IGNORE : ‘ , iconv ( «UTF-8» , «ISO-8859-1//IGNORE» , $text ), PHP_EOL ;
echo ‘Обычное преобразование : ‘ , iconv ( «UTF-8» , «ISO-8859-1» , $text ), PHP_EOL ;
Результатом выполнения данного примера будет что-то подобное:
Исходная строка : Это символ евро - '€'. С добавлением TRANSLIT : Это символ евро - 'EUR'. С добавлением IGNORE :Это символ евро - ''. Обычное преобразование : Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
iconv
Преобразует набор символов строки str из кодировки in_charset в out_charset .
Список параметров
Требуемая на выходе кодировка.
Если добавить к out_charset строку //TRANSLIT, включается режим транслитерации. Это значит, что в случае, если символ не может быть представлен в требуемой кодировке, он будет заменен на один или несколько нескольких наиболее близких по внешнему виду символов. Если добавить строку //IGNORE, то символы, которые не могут быть представлены в требуемой кодировке, будут удалены. В случае отсутствия вышеуказанных параметров при наличии некорректных символов строка str будет обрезана до первого такого символа, и будет сгенерирована ошибка уровня E_NOTICE .
Строка, которую необходимо преобразовать.
Возвращаемые значения
Возвращает преобразованную строку или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования iconv()
echo ‘Original : ‘ , $text , PHP_EOL ;
echo ‘TRANSLIT : ‘ , iconv ( «UTF-8» , «ISO-8859-1//TRANSLIT» , $text ), PHP_EOL ;
echo ‘IGNORE : ‘ , iconv ( «UTF-8» , «ISO-8859-1//IGNORE» , $text ), PHP_EOL ;
echo ‘Plain : ‘ , iconv ( «UTF-8» , «ISO-8859-1» , $text ), PHP_EOL ;
Результатом выполнения данного примера будет что-то подобное:
Original : This is the Euro symbol '€'. TRANSLIT : This is the Euro symbol 'EUR'. IGNORE : This is the Euro symbol ''. Plain : Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7 This is the Euro symbol '
How to resolve the error «iconv(): Wrong charset, conversion from UTF7-IMAP to UTF-8//IGNORE is not allowed» on PHP and Laravel
When working with different character encodings in PHP and Laravel, you might encounter errors on charset convertion like the following: iconv(): Wrong charset, conversion from ‘UTF7-IMAP’ to ‘UTF-8//IGNORE’ is not allowed
This error occurs when attempting to use the iconv() function to convert a string from the ‘UTF7-IMAP’ charset to ‘UTF-8//IGNORE’ charset. In this article, we’ll explore the possible causes of this error and provide solutions to fix it.
Causes of the Error iconv(): Wrong charset, conversion from ‘UTF7-IMAP’ to ‘UTF-8//IGNORE’ is not allowed
There could be a few possible reasons for this error:
- Missing or outdated iconv extension: The PHP iconv extension might not be installed or enabled on your system, or it may be outdated. Ensure that the extension is installed, enabled, and up-to-date.
- Unsupported charset: The ‘UTF7-IMAP’ charset might not be supported by your system’s iconv implementation. Different systems may have different character encoding support in their iconv libraries.
Solutions to Fix the Error iconv(): Wrong charset, conversion from ‘UTF7-IMAP’ to ‘UTF-8//IGNORE’ is not allowed
Install or enable the iconv php extension
To install or enable the iconv extension, follow these steps:
a. If you don’t have the iconv php extension installed, install it using your package manager. For example, on Ubuntu/Debian/Mint systems, you can run:
sudo apt-get install php-iconv
b. If you’re using multiple PHP versions, you’ll need to specify the PHP version for which you want to install the extension. For example, to install the iconv extension for PHP 7.4, run:
sudo apt-get install php7.4-iconv
c. If the extension is installed but disabled, you can enable it by updating the php.ini configuration file. Find and uncomment (remove the leading semicolon) the line:
Restart your web server after making any changes to the php.ini file.
Use an alternative function for charset conversion:
If the iconv() function does not support the ‘UTF7-IMAP’ charset, you can try using the mb_convert_encoding() function from the mbstring php extension:
$input = "Your UTF7-IMAP encoded string"; $output = mb_convert_encoding($input, "UTF-8", "UTF7-IMAP");
If you don’t have the mbstring php extension installed, you can install it using your package manager. For example, on Ubuntu/Mint/Debian systems, you can run:
sudo apt-get install php-mbstring
Remember to restart your web server after installing the extension.
By following these steps, you should be able to fix the error and successfully convert your string from the ‘UTF7-IMAP’ charset to ‘UTF-8//IGNORE’ charset.
Installing iconv and mbstring php extensions on Windows, Linux Ubuntu and Mint, MacOs
Now, let’s see how to install the required php extensions on various operating systems and environments.
Installing iconv and mbstring on Linux Debian based
Installing iconv and mbstring php extensions on Linux: Ubuntu/Debian/Mint
Install iconv and mbstring extensions:
sudo apt-get install php-iconv php-mbstring
If using multiple PHP versions, specify the desired version:
sudo apt-get install php7.4-iconv php7.4-mbstring
Installing iconv and mbstring on CentOs
Install iconv and mbstring extensions:
sudo yum install php-iconv php-mbstring
If using multiple PHP versions, specify the desired version:
sudo yum install php74-iconv php74-mbstring
Installing iconv and mbstring on MacOs
If using Homebrew, you can install the extensions with the following command:
brew install php-iconv php-mbstring
If using multiple PHP versions, specify the desired version:
Installing iconv and mbstring on Windows XAMPP
- Open the php.ini file located in the xampp\php directory.
- Find and uncomment the following lines by removing the leading semicolon:
;extension=iconv ;extension=mbstring
Installing iconv and mbstring on Windows WampServer
- Open the php.ini file located in the wamp\bin\php\php directory (replace with your PHP version).
- Find and uncomment the following lines by removing the leading semicolon:
;extension=iconv ;extension=mbstring
Save the php.ini file and restart the Apache server.
Final considerations
By following these steps, you should be able to fix the error and successfully convert your string from the ‘UTF7-IMAP’ charset to ‘UTF-8//IGNORE’ charset. Understanding and addressing the underlying causes of the error can help you ensure that your PHP and Laravel applications can handle different character encodings seamlessly.