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   ; and I would like these entities to be preserved in the XPath output.
$doc = new DOMDocument();
$doc->loadHTML('<html><head></head><body> Test</body></html>');
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//body');
foreac开发者_StackOverflow中文版h($nodes as $node) {
echo $node->textContent;
}
This code produces the following output (UTF-8):
[space]Test
But I would like to have this:
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?
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
to §nbsp;
.
An XPath processor isn't aware if a non-braking space character was specified as
or as  ' -- the character is always provided to it as a character entity --
`.
精彩评论