Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character encoding and using Zend\Dom\Query

I have a problem with the encoding of polish characters using Zend Framework 2. I use:

use Zend\Dom\Query;

Rest code:

$dom = new Query(); 
$document = '<ul id="test"><li>ęółąśłżźć</li><li>test</li></ul>';
$dom->setDocumentHtml($document);
$dom->setEncoding('utf-8');
$ul = $dom->execute('#test li');
foreach($ul as $li)
{
    echo $li->nodeValue;
}   

Result:

ÄóÅÄÅÅżźÄtest

enter image description here

How to display correctly these characters?

I tried to use PHP functions (iconv, utf8_encode) but without success.

like image 511
rafalli Avatar asked Aug 17 '26 10:08

rafalli


1 Answers

Under the hood Zend\Dom\Query uses DOMDocument which is built on libxml, whose HTML parser was made for HTML 4. The default encoding for which is ISO-8859-1.

Query::setEncoding() doesn't influence how a document is loaded.


Workarounds:

First use mb_convert_encoding to translate anything above the ASCII range into its html entity equivalent.

$dom->setDocumentHtml(mb_convert_encoding($document, 'HTML-ENTITIES', 'UTF-8'));

Or hack in a meta tag or xml declaration specifying UTF-8.

$dom->setDocumentHtml('<meta http-equiv="Content-Type" content="charset=utf-8" />' . $document);
$dom->setDocumentHtml('<?xml encoding="UTF-8">' . $document);
like image 132
user3942918 Avatar answered Aug 18 '26 23:08

user3942918



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!