HTML表格到CSV(包括页眉和页脚) - PHP

时间:2013-11-18 22:33:33

标签: php html csv

当我遇到这段代码时,我正在网上浏览,寻找在PHP中执行此操作的方法:

    preg_match('/<table(>| [^>]*>)(.*?)<\/table( |>)/is',$this->raw('./PayrollReportTable.report'),$b);
    $table = $b[2];
    preg_match_all('/<tr(>| [^>]*>)(.*?)<\/tr( |>)/is',$table,$b);
    $rows = $b[2];
    foreach ($rows as $row){
        preg_match_all('/<td(>| [^>]*>)(.*?)<\/td( |>)/is',$row,$b);
        $out[] = strip_tags(implode(',',$b[2]));
    }
    $out = implode("\n", $out);
    var_dump($out);

它做了我想要接受的两件事,示例中缺少多个页眉和页脚,因为它设计用于基本表。现在我在Rejex很恐怖,我很好奇,如果有人可以帮助我添加或解释添加表格标题的过程(此表格将有三个标题)和页脚(一个页脚)。

$this->raw('./PayrollReportTable.report')是要转换为csv的实际HTML表。到目前为止,这只会转换所有不是标题和页脚的内容,这很好,但是“我错过了其他组件。”

1 个答案:

答案 0 :(得分:3)

使用DOMDocumentDOMXPath而不是使用preg_match。

$domdoc = new DOMDocument();
$domdoc->loadHTML('yourstuff');

$xpath = new DOMXPath($docdoc);


foreach($xpath->query('//tr') as $tr) {
 // etc
}
相关问题