简体   繁体   English

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

[英]HTML Table to CSV (inc. Headers and footers) - PHP

I was surfing around the net looking for a way to do this in PHP when I came across this piece of code: 当我遇到这段代码时,我正在网上冲浪,寻找一种在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);

It does what I want accept for two things, multiple headers and footer are missing from the example as it is designed to work with basic tables. 它确实满足了我希望接受的两件事,该示例旨在与基本表一起使用,因此缺少示例中的多个页眉和页脚。 Now I am horrible at Rejex and I am curious if some one could help me out in adding or explaining what the process for adding the headers of a table (this table will have three headers) and the footer (one footer). 现在,我对Rejex感到非常恐惧,我很好奇是否有人可以帮助我添加或解释添加表标题(此表将包含三个标题)和页脚(一个页脚)的过程。

the $this->raw('./PayrollReportTable.report') is the actual HTML table to be converted to csv. $this->raw('./PayrollReportTable.report')是要转换为csv的实际HTML表。 So far this only converts everything that's not a header and a footer, which is great, cept' I am missing the other components. 到目前为止,这仅转换了不是页眉和页脚的所有内容,这很好,除非我缺少其他组件。

Rather than using preg_match use DOMDocument and DOMXPath . 而不是使用preg_match,而是使用DOMDocumentDOMXPath

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

$xpath = new DOMXPath($docdoc);


foreach($xpath->query('//tr') as $tr) {
 // etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM