How to convert string to utf8 format in php

醉折花枝作酒筹
Release: 2023-03-09 10:12:01
Original
2982 people have browsed it

Method: 1. Use iconv function, syntax "iconv(original character type, 'UTF-8', string)"; 2. Use mb_convert_encoding function, syntax "mb_convert_encoding(string, 'UTF-8" ', original character type)".

How to convert string to utf8 format in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

1. Use the iconv() function
iconv function can convert a known character set file into another known character set file. For example: Convert from GB2312 to UTF-8. iconv will make an error when converting the characters "—" to "gb2312". The solution is to add "//IGNORE" after the encoding that needs to be converted, which is the second iconv function. parameters. As follows:

 iconv("UTF-8", "GB2312//IGNORE", $data)
Copy after login

ignore means to ignore errors during conversion. Without the ignore parameter, all strings following this character cannot be saved.

 <?php 
  echo $str= ‘你好,这里是卖咖啡!&#39;; 
  echo &#39;<br />&#39;; 
  echo iconv(&#39;GB2312&#39;, &#39;UTF-8&#39;, $str); //将字符串的编码从GB2312转到UTF-8 
?>
Copy after login

2. Use "mb_convert_encoding" to convert the string into the UTF8 character set

When using mb_convert_encoding, you must first know the character encoding. If If the encoding is wrong, the characters will be garbled. Use mb_detect_encoding to automatically identify the string encoding and convert it to the international standard encoding utf-8 encoding.

<?php
    $encode = mb_detect_encoding($str, array("ASCII",&#39;UTF-8&#39;,"GB2312","GBK",&#39;BIG5&#39;,&#39;LATIN1&#39;));
    if($encode != &#39;UTF-8&#39;){
    $name = mb_convert_encoding($name, &#39;UTF-8&#39;, $encode);
  }
?>
Copy after login

Recommended tutorial: php video tutorial

The above is the detailed content of How to convert string to utf8 format in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
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!