Search code examples
phpmysqlimport-from-excel

Import Data from Excel in PHP


I want to import data from excel file using PHP and then if possible, save it to a MySQL database.


Solution

  • Importing from Excel files (XLS) is way harder than improting from CSV files. Usually I save my XLS to CSV with Excel then work on this CSV with PHP...

    Look at PHP function fgetcsv at: http://ca.php.net/manual/en/function.fgetcsv.php

    <?php
    $row = 1;
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
            }
        }
        fclose($handle);
    }
    ?> 
    

    If you still want to load XLS directly from PHP it's possible (but how reliable)... A quick seach resulted in http://sourceforge.net/projects/phpexcelreader/ which might be helpful.