search
HomeBackend DevelopmentPHP TutorialHow to solve php encoding conversion garbled characters

This article mainly shares with you how to solve php encoding conversion garbled code, combining text and code, I hope it can help everyone.

iconv Detailed explanation:
iconv - String is converted according to the required character encoding
iconv has a bug, and it will not be able to convert some rare characters. Of course, when configuring the second parameter, you can make up for the default defects a little, so that it will not be unable to convert or truncate. The usage is as follows
iconv("UTF-8″, "GB2312//IGNORE",$data);
When encountering a rare word conversion failure, it will ignore the failure and continue to convert the following content.

iconvstring iconv ( string $in_charset , string $out_charset , string $str )

第一个参数:内容原的编码

第二个参数:目标编码

第三个参数:要转的字符串

函数返回字符串<?php$instr = ‘测试’;// GBK转UTF-8$outstr = iconv(‘GBK’,&#39;UTF-8′,$instr);

?>

Return value
Returns the converted string, or returns FALSE on failure.

mb_convert_encoding detailed explanation:
In order to ensure the success rate of conversion, we can use another conversion function
mb_convert_encoding, this The efficiency of the function is not very high. In addition, this function can also omit the third parameter and automatically identify the content encoding. However, it is best not to use it, which will affect the efficiency. You also need to pay attention to the fact that the order of mb_convert_encoding and iconv parameters is different, so be sure to pay attention.

Attached are the simple usage of two functions:

mb_convert_encoding
string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )
第一个参数:要处理的字符串
第二个参数:目标编码
第三个参数:内容原编码,它可以是一个 array 也可以是逗号分隔的枚举列表<?php$instr = &#39;测试&#39;;
// GBK转UTF-8$outstr = mb_convert_encoding($instr,&#39;UTF-8&#39;,&#39;GBK&#39;,);
$str = mb_convert_encoding($instr, "UCS-2LE", "JIS, eucjp-win, sjis-win");?>

##Personal suggestions when encountering transcoding problems It is safer to use mb_convert_encoding.

mb_convert_variables

mb_convert_variables —

Convert the character encoding of one or more variables

mb_convert_variables ( $to_encoding , $from_encoding , &$vars [, mixed &$... ] )

will The encoding of variable vars is converted from from_encoding to encoding to_encoding.

mb_convert_variables() 会拼接变量数组或对象中的字符串来检测编码,因为短字符串的检测往往会失败。因此,不能在一个数组或对象中混合使用编码。
to_encoding  将 string 转换成这个编码。

from_encoding 可以指定为一个 array 或者逗号分隔的 string,它将尝试根据 from-coding 来检测编码。 当省略了 from_encoding,将使用 detect_order。
vars 是要转换的变量的引用。 参数可以接受 String、Array 和 Object 的类型。 mb_convert_variables() 假设所有的参数都具有同样的编码。
额外的 vars。
返回值 :
成功时返回转换前的字符编码,失败时返回 FALSE。
实例:<?php/* 转换变量 $post1、$post2 编码为内部(internal)编码 
*/$interenc = mb_internal_encoding();$inputenc = mb_convert_variables($interenc,
 "ASCII,UTF-8,SJIS-win", $post1, $post2);?>

##mb_internal_encoding mb_internal_encoding — Set/get internal character encoding

mixed mb_internal_encoding ([ string $encoding = mb_internal_encoding() ] )
参数 :
encoding 字符编码名称使用于 HTTP 输入字符编码转换、HTTP 输出字符编码转换、mbstring 模块系列函数字符编码转换的默认编码。 
返回值 :
如果设置了 encoding,则成功时返回 TRUE, 或者在失败时返回 FALSE。 In this case, the character encoding for multibyte regex is NOT changed. 如果省略了 encoding,则返回当前的字符编码名称。
<?php/* 设置内部字符编码为 UTF-8 */mb_internal_encoding("UTF-8");/* 显示当前的内部字符编码*/echo mb_internal_encoding();?>

Detailed explanation of mb_detect_encoding: mb_detect_encoding —

Encoding of detected characters

string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )
  • 1

检测字符串 str 的编码。

参数 
str    待检查的字符串。
encoding_list   是一个字符编码列表。 编码顺序可以由数组或者逗号分隔的列表字符串指定。
如果省略了 encoding_list 将会使用 detect_order。strict    strict 指定了是否严格地检测编码。 默认是 FALSE。
返回值
检测到的字符编码,或者无法检测指定字符串的编码时返回 FALSE。

字符串编码未知的情况下对字符串进行编码: 
1、无论字符串编码是什么,均转换为gbk

function getSafeStr($str){
    $s1 = iconv(&#39;utf-8&#39;,&#39;gbk//IGNORE&#39;,$str);    $s0 = iconv(&#39;gbk&#39;,&#39;utf-8//IGNORE&#39;,$s1);    if($s0 == $str){        return $s1;
    }else{        return $str;
    }
}

2、无论字符串编码是什么,均转换为utf-8

function getSafeStr($str){
    $s1 = iconv(&#39;gbk&#39;,&#39;utf-8//IGNORE&#39;,$str);    $s0 = iconv(&#39;utf-8&#39;,&#39;gbk//IGNORE&#39;,$s1);    if($s0 == $str){        return $s1;
    }else{        return $str;
    }
}

获取字符串编码方法:

function getcode($str){
    $s1 = iconv(&#39;utf-8&#39;,&#39;gbk//IGNORE&#39;,$str);    $s0 = iconv(&#39;gbk&#39;,&#39;utf-8//IGNORE&#39;,$s1);    if($s0 == $str){        return &#39;utf-8&#39;;
    }else{        return &#39;gbk&#39;;
    }
}

The above is the detailed content of How to solve php encoding conversion garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version