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:

    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).

the $this->raw('./PayrollReportTable.report') is the actual HTML table to be converted to csv. So far this only converts everything that's not a header and a footer, which is great, cept' I am missing the other components.

Answers


Rather than using preg_match use DOMDocument and DOMXPath.

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

$xpath = new DOMXPath($docdoc);


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

Need Your Help

Razor Syntax and Javascript

javascript razor asp.net-mvc-3

As a test I'm converting a proof-of-concept app we've written from Web Forms to Razor, simply so we can evaluate it.

Full size horizontal progressbar in layout when running Android 2.x

android android-layout android-progressbar android-compatibility

The following is a very simplified layout for a list view item that works as expected running on multiple different android 4.x devices but not on android 2.3 (device and emulator).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.