【问题标题】:Php Simple HTML DOM Parser - how to work with block repeatsPhp Simple HTML DOM Parser - 如何处理块重复
【发布时间】:2017-03-29 18:10:49
【问题描述】:

我有 <h2> 块但没有属性。之后去块<p> 没有属性。

这个结构是这样的:

<h2></h2>
<p></p>
<p></p>
<p></p>
<h2></h2>
<p></p>
<p></p>
<h2></h2>
<p></p>

我正在使用 Php Simple HTML DOM Parser。我想从&lt;h2&gt; 块中获取数据,然后将所有&lt;p&gt; 获取到另一个&lt;h2&gt; 等等。

但所有&lt;h2&gt; 都必须连接到&lt;p&gt;,后者会追随它们。我想使用key =&gt; value(例如&lt;h2&gt; =&gt; &lt;p&gt;,&lt;p&gt;,... 和另一个&lt;h2&gt;),但我不知道该怎么做。

另外,我知道next_sibling(),但不知道如何在循环中使用它。我做了 2 个变量,第一个有所有 &lt;h2&gt;,第二个有 &lt;p&gt;。我认为这对我的目标很有用。代码如下:

$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
  echo $test2 . '<br>';
  foreach($test->find('p') as $test3) {
    echo $test3 .'<br>';
  }
}

【问题讨论】:

  • Robin Mackenzie,谢谢,您编辑了我的问题。))

标签: php parsing dom foreach simple-html-dom


【解决方案1】:

不清楚您在寻找什么,但这里有一个想法可以帮助您入门:

foreach($html->find('h2') as $el){
  $h2 = $el;
  while($el = $el->next_sibling()){
    if('p' != $el->tag) break;
    // do something
  }
}

【讨论】:

    【解决方案2】:

    在这里回答我的问题。我希望它可以帮助别人!)

     `foreach ($html->find('.div') as $div)
        {
            if(!$next=$div->next_sibling()) continue;
                if($next->tag==='h2')
                {
                    $h2 =$next;
                    echo $h2;
    
                    while ($h2 = $h2->next_sibling())
                    {
                        if(!$h2->tag=='p') break;
                        {
                            $p =$h2;
                            echo $p;  
                        }     
                    }
                    while ($h2 = $h2->next_sibling())
                    {
                        if(!$h2->tag=='table') break;
                        {
                            $tab =$h2;
                            echo $tab;
                        }     
                    }
                    while ($h2 = $h2->next_sibling())
                    {
                        if(!$h2->tag=='ul') break;
                        {
                            $ul =$h2;
                            echo $ul;
                        }     
                    }
                }
                else continue;
        }`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2019-09-21
      相关资源
      最近更新 更多