Q:

How to parse a PHP variable that has HTML markup into CSV?

I have a database field that has a value that contain HTML tables (essentially a wysiwyg field). So a good $example variable would be the following table.
<table class='product_data'>
<tr class='odd'>
    <td>2002</td>
    <td>2006</td>
    <td>ACURA</td>
</tr>
<tr class='odd'>
    <td>2002</td>
    <td>2006</td>
    <td>HONDA</td>
</tr>
<tr class='odd'>
    <td>2002</td>
    <td>2006</td>
    <td>TOYOTA</td>
</tr>
</table>

Im using PHP to read the data from the database. The goal is to parse this database field into a csv file. In this example, there are 3 rows. So output csv file should be:
 2002-2006,ACURA
 2002-2006,HONDA
 2002-2006,TOYOTA

Is there a simple way that can be done in PHP? I'm sure there is but nothing off top of my head. 

A:

Download http://sourceforge.net/projects/simplehtmldom/files/simple_html_dom.php/download
Put the downloaded file in the same folder as the following file
parser.php
<?php
include "simple_html_dom.php";
$table = "<table class='product_data'>
    <tr class='odd'>
        <td>2002</td>
        <td>2006</td>
        <td>ACURA</td>
    </tr>
    <tr class='odd'>
        <td>2002</td>
        <td>2006</td>
        <td>HONDA</td>
    </tr>
    <tr class='odd'>
        <td>2002</td>
        <td>2006</td>
        <td>TOYOTA</td>
    </tr>
</table>";

$html = str_get_html($table);

header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=yourfilename.csv');

$fp = fopen("php://output", "w");

foreach ($html->find('tr') as $element) {

    $td = array();
    foreach ($element->find('td') as $row) {
        $td [] = $row->plaintext;
    }
    fputcsv($fp, $td);
}

fclose($fp);

