Olivier Lalonde
Olivier Lalonde

Reputation: 19908

PHP encoding with DOMDocument

<tag>
Алекс М
</tag>

When I try to get the content of the following code using DOMDocument functions, it returns something like:

ÐÐ»ÐµÐºÑ Ðœ

I've tried setting DOMDocument encoding to different values (UTF-8, ISO-8859-1), using mb_convert_encoding, iconv and utf8_encode but without success.

How can I get "Алекс М" instead of "ÐÐ»ÐµÐºÑ Ðœ" ?

EDIT: The input is coming from a page loaded with curl. When I output the page content to my browser, the characters are displayed correctly (so I doubt the input is the problem).

Upvotes: 24

Views: 24375

Answers (4)

Simao Gomes Viana
Simao Gomes Viana

Reputation: 621

If you're parsing HTML body content, wrap it in a full HTML document. For example, if your content is UTF-8, use this function and pass your HTML to it:

function wrapHTMLContentInUTF8Container( string $content ): string {
    return <<<HTML
        <!doctype html>
        <html lang="C">
            <head>
                <title></title>
                <meta charset="utf-8">
            </head>
            <body>$content</body>
        </html>
    HTML;
}

Use it like this:

$dom->loadHTML(wrapHTMLContentInUTF8Container($yourHTML));

This way the parser knows it's UTF-8 since it's explicitly specified in the HTML document and it will know how to handle Unicode.

Upvotes: 1

Nemke
Nemke

Reputation: 415

I had a similar problem after using XPath to parse DomDocument, and after reading this

https://bugs.php.net/bug.php?id=32547

I solved it like this

// Workaround because PHP 5.2.x has encoding problems, when we 
// update to PHP 5.3 this line is not necesserry any more
$content = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . $content;

// Creating new DOM document and loading HTML content
$dom_document = new DOMDocument('1.0', 'UTF-8');
$dom_document->substituteEntities = TRUE;
$dom_document->loadHTML($content);

Upvotes: 19

Ilia Kondrashov
Ilia Kondrashov

Reputation: 746

Add xml header to you tags - try this:

$a = new DOMDocument ();
$a->loadXml ('<?xml version="1.0" encoding="UTF-8"?><tag>Алекс М</tag>');
print htmlspecialchars ($a->saveXml ());

Upvotes: 5

Dmytro Zavalkin
Dmytro Zavalkin

Reputation: 5277

Try:

$string = file_get_contents('your-xml-file.xml');
$string = mb_convert_encoding($string, 'utf-8', mb_detect_encoding($string));
// if you have not escaped entities use
$string = mb_convert_encoding($string, 'html-entities', 'utf-8'); 
$doc = new DOMDocument();
$doc->loadXML($string);

Upvotes: 47

Related Questions