Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent DOMXPath from expanding HTML entities?

I'm using DOMDocument and DOMXPath in PHP to find elements in an HTML document. This document contains HTML entities like &nbsp ; and I would like these entities to be preserved in the XPath output.

$doc = new DOMDocument();
$doc->loadHTML('<html><head></head><body>&nbsp;Test</body></html>');

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//body');

foreach($nodes as $node) {
    echo $node->textContent;
}

This code produces the following output (UTF-8):

[space]Test

But I would like to have this:

&nbsp;Test

Maybe it has something to do with LibXML that PHP uses internally, but I couldn't find any function that preserves the HTML entities.

Do you have an idea?

like image 687
klaussner Avatar asked May 15 '11 09:05

klaussner


2 Answers

XPath always sees a representation of the XML document in which entity references have been expanded. The only way to prevent this is to preprocess the XML document, replacing the entity references by something that won't be expanded, for example changing &nbsp; to §nbsp;.

like image 84
Michael Kay Avatar answered Oct 04 '22 20:10

Michael Kay


An XPath processor isn't aware if a non-braking space character was specified as &nbsp; or as &#xA0;' -- the character is always provided to it as a character entity -- `.

like image 34
Dimitre Novatchev Avatar answered Oct 04 '22 21:10

Dimitre Novatchev