Convert HTML table to CSV

Just a quick one – I needed a script to convert a table to a csv, so this is what I came up with. See the annotations for notes:

//html table is in variable $report
$report = str_replace(array("\n", "\r"), "", $report); //remove existing line breaks
$report = str_replace('"', '\"', $report); //escape existing quote marks
$csv_lines = explode('</tr>', $report); //explode by end of table row
$csv_report = ''; //define output
  foreach ($csv_lines as $this_line) { //each row
  $csv_cells = explode('</td>', $this_line); //explode by end of table cell
  $csv_newcells = array(); //define new cells
    foreach ($csv_cells as $this_cell) { //each cell
    $this_cell = strip_tags($this_cell); //remove any html tags
    $this_cell = html_entity_decode($this_cell); //remove any html characters
    $this_cell = trim($this_cell); //trim any whitespace
      if (!is_numeric($this_cell)) $this_cell = '"'.$this_cell.'"'; //encapsulate in quotes if it is not a number
    $csv_newcells[] = $this_cell; //add it to the new cell array
    } //foreach cell
  $csv_report .= implode(',', $csv_newcells)."\r\n"; add the new cell line to the output
  } //foreach line
echo $csv_report;

Tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *