Fordnox

Life is about trust

Subscribe to Fordnox
Technorati
del.icio.us
May-15-08

Excel table to PHP array

posted by Andrius

This little function converts string copied from Excel to PHP array. This is useful if you don’t have posibility to work with PHP5 (or higher).

function parse_excel_string($string, $columnheadings = false, $delimiter = "\t", $enclosure = "\n") {
        $row_index = 0;
        $rows = array();
        $array_of_rows = explode($enclosure, rtrim($string));
        if(is_array($array_of_rows) && !empty($array_of_rows)) {
            if($columnheadings == true) {
                $headings = explode($delimiter, rtrim($array_of_rows[0]));
            }
            foreach ($array_of_rows as $row) {
                $row_values = explode($delimiter, rtrim($row));
                if($headings && is_array($headings) && !empty($headings)) {
                    for($i=0;$i<sizeof ($headings);$i++) {
                        $rows[$row_index][$headings[$i]] = $row_values[$i];
                    }
                } else {
                    for($j=0;$j<sizeof($row_values);$j++) {
                        $rows[$row_index][$j] = $row_values[$j];
                    }
                }
                $row_index++;
            }
            if($columnheadings === true) {
                unset($rows[0]);
            }
            $rows = array_values($rows);
            return $rows;
        } else {
            return false;
        }
    }