简单的dom解析器导致多个页面

时间:2019-03-16 09:19:01

标签: php parsing dom

我已经解析了一个页面以获取标题,有时解析的标题超过11个。我设计的模板最多包含11个标题。我的问题是如何为其余标题(从12-> n)复制模板()。对于其余结果,我必须以某种方式复制模板,但我不知道该怎么做。 贝娄是我的模板,女巫正在显示所有结果。

<?php 
    include('parse/simple_html_dom.php'); 
    $url = 'link-to-url';
    $html = file_get_html($url);
    $headlines = array();
    $i = 0;
?>
<div class="pf w0 h0">
    <div class="w0 h0">
        <div class="header-pagina">
            <svg role="img"  class="header37"><use xlink:href="#header-hp"></use></svg>
        </div>

        <div class="page-wrapper">
            <?php 
           foreach($html->find('.cmsmasters_row[1] .cmsmasters_toggle_title') as $title) {
                    $i++;
                        echo '<div class="agenda-curs">';
                        echo '<div class="agenda-tab"><span class="modul-tab-text color1" contenteditable="true">Modulul '.$i.'</span></div>';   
                        echo '<div class="agenda-text" contenteditable="true">'.$headlines[] = $title->plaintext.'</div >';

                        echo '</div>';
            }
            $head = implode("", $headlines);
            ?>
        </div>
        <svg role="img" class="footer35"><use xlink:href="#footer35"></use></svg>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

我不知道您在脚本中使用$head = implode("", $headlines);做什么,但是您将能够从下面的$headlinesheadline_batch收集所需的数据。

将处理与打印分开将使您的代码更易于阅读和维护。我可以编写脚本以使用更少的循环,但是我更喜欢可读性而不是效率。

<?php 
include('parse/simple_html_dom.php'); 
$url = 'link-to-url';
$html = file_get_html($url);
$headlines = array();
$counter = 0;
foreach($html->find('.cmsmasters_row[1] .cmsmasters_toggle_title') as $title) {
    $headlines[++$counter] = $title->plaintext;
}

// no more processing, just printing
foreach (array_chunk($headlines, 10, true) as $headline_batch) {
    ?>
    <div class="pf w0 h0">
        <div class="w0 h0">
            <div class="header-pagina">
                <svg role="img"  class="header37"><use xlink:href="#header-hp"></use></svg>
            </div>
            <?php

            foreach ($headline_batch as $counter => $title) {
                echo '<div class="agenda-curs">
                          <div class="agenda-tab"><span class="modul-tab-text color1" contenteditable="true">Modulul ' . $counter . '</span></div>
                          <div class="agenda-text" contenteditable="true">' . $title . '</div >
                      </div>';
            }

            ?>
            </div>
            <svg role="img" class="footer35"><use xlink:href="#footer35"></use></svg>
        </div>
    </div>
    <?php
}
?>

使用array_chunk($headlines, 10, true)将使您不必在循环中使用模数条件来检查是否应开始新的组。分组后,true参数将保留$counter值。

相关问题