开发者

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');

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:

&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?


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;.


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 -- `.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜