Here’s a script which I wrote today while on the jorb.  The purpose was so that someone could copy and paste from an excel spreadsheet into a textarea, click a button, and voila: an html table.

The nice thing was that when I pasted Excel data into the textarea, it was tab-delimited with line breaks.  At that point, all I needed to do was some replacements and throw a table wrapper on it.

Here’s the code for the conversion function (sorry – i haven’t installed a php code parser yet to style this more nicely):

<?php
/**
* convert tab delimited file to html table
* @input string tab-delimited text
* found at http://james.revillini.com
* note: you are not required to keep the above copyright notice in this code.
*/
function tabs_to_table($input) {
//define replacement constants
define(‘TAB_REPLACEMENT’, ‘</td><td> ‘);
define(‘NEWLINE_REPLACEMENT’, ‘</td></tr><tr%s><td> ‘);
define(‘TABLE_BEGIN’, ‘<table><tr><td> ‘);
define(‘TABLE_END’, ‘</td><tr></table>’);</code>

//replace all tabs with end-cell, begin-cell
$input = preg_replace  (’/\t/’  , TAB_REPLACEMENT  , $input);

//split the list on linebreaks
$rows = preg_split  (’/\r\n/’  , $input);

//replace all linebreaks with end-row, begin-row (with or without altRow class)
$output = ”;
foreach ($rows as $index => $row) {
$output .= $row . sprintf(NEWLINE_REPLACEMENT, ($index%2?”:’ class=”alt”‘));
}

//build table
$input = TABLE_BEGIN . $output . TABLE_END;
return ($input);
}
?>