How to convert UTF-8 and ISO-8859-1 strings in PHP?

Susan Sarandon
Release: 2024-11-02 09:05:03
Original
416 people have browsed it

How to convert UTF-8 and ISO-8859-1 strings in PHP?

Converting UTF-8 and ISO-88591 in PHP

When scripts with different encodings require interaction, it becomes crucial to convert characters between different formats. PHP provides several functions to facilitate such conversions.

Converting UTF-8 to ISO-88591

To convert a UTF-8 string to ISO-88591, you can use the iconv() or mb_convert_encoding() functions. These functions require specific extensions: ext/iconv for iconv() and ext/mbstring for mb_convert_encoding().

<code class="php">$utf8 = 'ÄÖÜ'; // in a UTF-8 encoded file

// Using iconv()
$iso88591 = iconv('UTF-8', 'ISO-8859-1', $utf8);

// Using mb_convert_encoding()
$iso88591 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');</code>
Copy after login

Converting ISO-88591 to UTF-8

To convert an ISO-88591 string to UTF-8, you can also use iconv() or mb_convert_encoding().

<code class="php">$iso88591 = 'ÄÖÜ'; // in an ISO-8859-1 encoded file

// Using iconv()
$utf8 = iconv('ISO-8859-1', 'UTF-8', $iso88591);

// Using mb_convert_encoding()
$utf8 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');</code>
Copy after login

An Alternative: utf8_encode() and utf8_decode()

The utf8_encode() and utf8_decode() functions may not be suitable for your specific scenario because:

  • utf8_decode() converts ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1, which may not be what you want.
  • utf8_encode() encodes ISO-8859-1 strings to UTF-8, whereas you need the reverse conversion.

Therefore, using iconv() or mb_convert_encoding() is more appropriate for converting between UTF-8 and ISO-88591.

The above is the detailed content of How to convert UTF-8 and ISO-8859-1 strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!