drn1008 2013-07-23 22:45
浏览 56
已采纳

DOMDocument获取每个匹配元素的nodeValue

I've been hacking at this for a while and just cant seem to get it right.

How can you get get the contents of all script elements, when the number of script elements is variable. My example markup looks like this:

<div></div>
<iframe><iframe>
<script>xxxx</script>
<script>xxxx</script>
<script>xxxx</script>

What I have so far works only if I keep the number of scripts static so clearly Im not iterating over the array correctly, but Im totally thrown by the DOMXPath documentation as how to do it. This is what I have so far:

$dom = new DOMDocument();
$dom->preserveWhiteSpace = true;
@$dom->loadHtml($form_content);
$xpath = new DOMXPath($dom);
$items = $xpath->query('//script');
foreach ($items as $item) {
     $scriptContents = $item->previousSibling->previousSibling->nodeValue . "\    n
";
     $scriptContents .= $item->previousSibling->nodeValue . "

";
     $scriptContents .= $item->nodeValue . "

";
}
echo $scriptContents;

How should I go about this? I've been search SO for a while now, but can seem to apply a solution that works. Thanks in advance - b

  • 写回答

1条回答 默认 最新

  • douzuita7325 2013-07-24 15:26
    关注

    It appears that you are overwriting $scriptContents with each iteration, which is probably not what you are intending. The way the script currently is operating, your output would be limited to the two previous siblings of the last script tag (whether or not they are actually script tags themselves) along with the last script tag.

    If you are strictly trying to output the script tags you can do this:

    $xpath = new DOMXPath($dom);
    $items = $xpath->query('//script');
    foreach ($items as $item) {
         echo $item->nodeValue . "
    
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向