为什么 getElementsByTagName 只抓取这里的所有其他元素?
通过使用 DomDocument 的此代码:
<?php
$html = '<pre>one</pre><pre>two</pre><pre>three</pre><pre>four</pre>';
$doc = new DomDocument();
$doc->loadHTML($html);
$sub = $doc->getElementsByTagName("pre");
foreach($sub as $pre) {
$fragment = $doc->createDocumentFragment();
$fragment->appendXML(str_replace('&', '&', '<p>& it\'s replaced</p>'));
$pre->parentNode->replaceChild($fragment, $pre);
}
echo $doc->saveHTML();
?>
我得到以下输出:
<p>& it's replaced</p>
<pre>two</pre>
<p>& it's replaced</p>
<pre>four</pre>
有人可以向我解释发生了什么以及为什么所有 pre
标签没有被替换吗?
With this code using DomDocument:
<?php
$html = '<pre>one</pre><pre>two</pre><pre>three</pre><pre>four</pre>';
$doc = new DomDocument();
$doc->loadHTML($html);
$sub = $doc->getElementsByTagName("pre");
foreach($sub as $pre) {
$fragment = $doc->createDocumentFragment();
$fragment->appendXML(str_replace('&', '&', '<p>& it\'s replaced</p>'));
$pre->parentNode->replaceChild($fragment, $pre);
}
echo $doc->saveHTML();
?>
I get this output:
<p>& it's replaced</p>
<pre>two</pre>
<p>& it's replaced</p>
<pre>four</pre>
Can someone explain to me what is going on and why all the pre
tags aren't being replaced?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试以下方式: http://codepad.viper-7.com/ALYWEi
我发现当我在没有引号的情况下搜索“DomDocument Replacechild”时出现的问题
请参阅此处的第一条评论: http://php.net/manual/en/domnode.replacechild.php 特别是这个:
You can try this way: http://codepad.viper-7.com/ALYWEi
I found the issue when I googled "DomDocument replacechild" without the quotes
see the first comment here: http://php.net/manual/en/domnode.replacechild.php particularly this:
这与方向有关:
不起作用,但
效果很好。我想一定有类似内部计数器的东西。
安德烈亚斯 HTH
It has something to do with the direction:
doesn't work but
works fine. There must be something like an internal counter, I reckon.
HTH Andreas