【问题标题】:Simple HTML DOM how to access the elements at the top level only简单的 HTML DOM 如何仅访问顶层的元素
【发布时间】:2011-03-04 13:51:32
【问题描述】:

我被主题问题困住了。 这是示例代码:

include('./simple_html_dom.php');
$html = str_get_html("
<cols>
    <br>
    <col>
        content1
        <br>
        content1
    </col>
    <br>
    <col>
        <br>
        content2
        <br>
        content2
    </col>
    <br>
</cols>");

foreach($html->find('cols br') as $br) { 回声 $br-> 外文; } 这给了我<cols> 标签内的所有<br> 标签,但我只需要顶层的<br>
$html->find('cols > br') 也不起作用(

更新 解决这个问题:

foreach($html->find('cols') as $cols_tag_content) {
    for($node = 0; $node < count($cols_tag_content->children()); $node++) {
        if($cols_tag_content->children($node)->tag == "br") {
            //doing whatever you want with br. i just remove it
            $cols_tag_content->children($node)->outertext = "";
        }
    }
}
这适用于&lt;br&gt;&lt;br /&gt;

【问题讨论】:

    标签: php html dom


    【解决方案1】:
    foreach($html->find('cols') as $cols_tag_content) {
        for($node = 0; $node < count($cols_tag_content->children()); $node++) {
            if($cols_tag_content->children($node)->tag == "br") {
                //doing whatever you want with br. i just remove it
                $cols_tag_content->children($node)->outertext = "";
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      你试过'cols>br'吗?我认为 'cols > br' 可能 把它扔掉了。

      更多信息请参见http://www.w3schools.com/css/sel_element_gt.asp

      我认为 jQuery 允许间距。

      更新

      我将上面的伪 html 重组为使用带有类的 div,如下所示:

      <div class="cols">
          <br />
          <div class="col">
              content1
              <br />
              content1
          </div>
          <br />
          <div class="col">
              <br />
              content2
              <br />
              content2
          </div>
          <br />
      </div>
      

      现在可以执行以下 jQuery 脚本:

      var brs= $('div.cols > br');
      alert("Found "+brs.length+" brs");
      

      【讨论】:

      • 感谢您的回复,是的,我已经尝试过了,不幸的是它也给了我全部 6 个&lt;br&gt;s
      • 啊!我明白你在说什么,让我再解释一下
      • 为什么不将您的
        更改为一些
        并使用类似 SimpleXML 的东西? :p
      • 1) 我无法更改我的标记。 2)SimpleXML 无法从全局角度解决我的问题,所以我需要使用 simple_html_dom。我解决了这个问题,如果有人有同样的问题,请更新第一篇文章。无论如何感谢您的回复:)
      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 2015-05-20
      • 2012-08-28
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多