php中DOMDocument对于xml操作我们只要是英文是没有问题了,但如果是中文字体就会有乱码问题了,下面我们就此问题给各位介绍一些解决办法吧.
PHP的DOM内部是utf8机制的,在loadHTML时,是通过检查字符中meta的charset来设置编码的,如果没有charset,就当iso8859进行处理了,而这种情况下进行saveXML时,输出来的却是utf8,所以就看到乱码了.
这么说是不是还不太理解,举个例子:
$xml = new DOMDocument(); @$xml->loadHTML('<div>我就是测试看看 - http://www.phprm.com</div>'); $dom = new DOMXPath($xml); echo $dom->query('//div')->item(0)->saveXML();
打开网页执行,你会发现输出乱码了,那如何解决这个问题呢?有两种方式.
第一种:在loadHTML的时候指定编码,下面这段代码引用自php.net官方文档中的回复,代码如下:
$doc = new DOMDocument(); $doc->loadHTML('<?xml encoding="UTF-8">' . $html); // dirty fix foreach ($doc->childNodes as $item) if ($item->nodeType == XML_PI_NODE) $doc->removeChild($item); // remove hack $doc->encoding = 'UTF-8'; // insert proper
第二种方法:通过iconv对输出的字符重新转换,代码如下:
echo iconv("UTF-8", "GB18030//TRANSLIT", $dom->saveXML($n) );
永久地址:
转载随意~请带上教程地址吧^^

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool