


How to correctly use the PHP json_encode function for Chinese conversion_PHP tutorial
What we will bring to you today is the solution to the problem when the PHP json_encode function handles Chinese conversion. json is a very good data structure and is now widely used in network data transmission.
json_encode and json_decode
There are many related information on the Internet about the specific usage of these two functions. article, this article mainly introduces the solution to the problem that Chinese cannot be converted when using json_encode. This article assumes that the encoding used in the file is gb2312;
Write the required array first
- ?PHP
- $ json = array (
- 0 =>
- array (
- 'id' => '13',
- 'name' => 'table tennis',
- ),
- 1 =>
- array (
- 'id' => '17',
- 'name' => 'Basketball',
- )
- )
- ?>
If you use the PHP json_encode function directly
<ol class="dp-xml"> <li class="alt"><span class="tag"> ?PHP </span></li> <li><span>echo json_encode($json); </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> <li><span> </span></li> </ol>
The result is:
<ol class="dp-xml"> <li class="alt"><span class="tag"> ?PHP </span></li> <li><span>[{"id":"13","name":null}<br>,{"id":"13","name":null}] </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> <li><span> </span></li> </ol>
You can see that all Chinese characters that are not escaped are null. This is because json only escapes encoding, so the above statement should convert the encoding first
<ol class="dp-xml"> <li class="alt"><span class="tag"> ?PHP </span></li> <li> <span>foreach ($ajax as $</span><span class="attribute">key</span><span>=</span><span class="tag">></span><span>$val) </span> </li> <li class="alt"><span>{ </span></li> <li><span>$ajax[$key]['name'] = <br>urlencode($val['name']); </span></li> <li class="alt"><span>} </span></li> <li><span>echo json_encode($json); </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
Client js code
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> </span><span class="tag-name">script</span><span> </span><span class="attribute">type</span><span>=</span><span class="attribute-value">"text/javascript"</span><span class="tag">></span><span> </span></span></span></li> <li><span>function getsort(obj) </span></li> <li class="alt"><span>{ </span></li> <li><span>$.ajax( </span></li> <li class="alt"><span>{ </span></li> <li><span>type : "GET", </span></li> <li class="alt"> <span>url : "</span><span class="tag"><span> ?=$this-</span><span class="tag">></span><span>baseUrl</span><span class="tag">?></span><span>/index/getajax", </span></span> </li> <li> <span>data : "</span><span class="attribute">c</span><span>=" obj.value, </span> </li> <li class="alt"><span>success : function(json) </span></li> <li><span>{ </span></li> <li class="alt"> <span>var </span><span class="attribute">json</span><span>=</span><span class="attribute-value">eval</span><span>(json); </span> </li> <li> <span>var </span><span class="attribute">html</span><span> = </span><span class="attribute-value">''</span><span>; </span> </li> <li class="alt"><span>$.each(json, function(k) </span></li> <li><span>{ </span></li> <li class="alt"> <span class="attribute">html</span><span> = </span><span class="attribute-value">'<span> <br>json[k]['id'] '"</span><span class="tag">></span><span>' <br>decodeURI(json[k]['name']) '</span><span class="tag"><span> /option</span><span class="tag">></span><span>'; </span></span></span> </li> <li><span>}); </span></li> <li class="alt"> <span class="attribute">html</span><span> =</span><span class="attribute-value">""</span><span>; </span> </li> <li><span>$('#sort').html(html); </span></li> <li class="alt"><span>} </span></li> <li><span>} </span></li> <li class="alt"><span>) </span></li> <li><span>} </span></li> <li class="alt"><span class="tag"><span> /script</span><span class="tag">></span><span> </span></span></li> </ol>
Using the above code js will report an error saying that the encoding does not comply The reason for standard
is because decodeURI in js only supports utf8 transcoding. Therefore, the code of the PHP json_encode function should be the following code
<ol class="dp-xml"> <li class="alt"><span class="tag"> ?PHP </span></li> <li> <span>foreach ($ajax as $</span><span class="attribute">key</span><span>=</span><span class="tag">></span><span>$val) </span> </li> <li class="alt"><span>{ </span></li> <li><span>$ajax[$key]['name'] = <br>urlencode(iconv('gb2312',<br>'utf-8',$val['name'])); </span></li> <li class="alt"><span>} </span></li> <li><span>echo json_encode($json); </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> <li><span> </span></li> </ol>
The above is using PHP json_encode Solutions to problems encountered in actual operation of functions.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.
