PHP Script: Convert Excel or tab-delimited file to html table | James Revillini

PHP Script: Convert Excel or tab-delimited file to html table

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

/**
* 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>&nbsp;');
define('NEWLINE_REPLACEMENT', '</td></tr><tr%s><td>&nbsp;');
define('TABLE_BEGIN', '<table><tr><td>&nbsp;');
define('TABLE_END', '</td><tr></table>');

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

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

//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);
}

"PHP Script: Convert Excel or tab-delimited file to html table" was published on January 30th, 2008 and is listed in php.

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

james.revillini.com