gpt4 book ai didi

php - 为什么 xpath 会删除 html 特殊字符?

转载 作者:可可西里 更新时间:2023-10-31 22:46:46 25 4
gpt4 key购买 nike

为什么会这样

$html = '<a href="/browse/product.do?cid=1&amp;vid=1&amp;pid=1" class="productItemName">what is going on here</a>';

$dom = new DOMDocument();
$dom->loadhtml($html);
$xpath = new DOMXPath($dom);

$selectors['link'] = '//a/@href';
$links_nodeList = $xpath->query($selectors['link']);

foreach ($links_nodeList as $link) {
$links[] = $link->nodeValue;
}

echo("<p>links</p>");
echo("<pre>");
print_r($links);
echo("</pre>");

输出

links

Array
(
[0] => /browse/product.do?cid=1&vid=1&pid=1
)

不是

links

Array
(
[0] => /browse/product.do?cid=1&amp;vid=1&amp;pid=1
)

?

最佳答案

答案很简单:

& 是在 XML 文档中表示字符 "&" 的一种特殊方式。

这两个表示相同的字符

当 & 符号的转义形式输出为文本(而不是 XML)时,将其显示为 "&" 是正确的。

@LarsH 在他的评论中进一步阐述:

when you say loadhtml($html);, you are parsing the string as HTML, which means that character entities (like &amp;) are interpreted into the characters they represent (like &). If you want a string that will be interpreted as &amp;, you need to escape the ampersand, e.g. &amp;amp;

关于php - 为什么 xpath 会删除 html 特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8897523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com