Php excel with csv

I been seeking the same thing. Excel CSV dosn’t always use the quote separators and escapes the quotes using «» because the algorithm was probably made back the 80’s or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval’d code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: tgearin2@gmail.com
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('r', 'n', 't', '\', '"');  //two byte escape codes
        $escapes2=array("r", "n", "t", "\", """); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="rn"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="rn"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."rn";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: tgearin2@gmail.com
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = ''
       $escapes=array('r', 'n', 't', '\', '"');  //two byte escape codes
       $escapes2=array("r", "n", "t", "\", """); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="rn";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="rn";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }

…Now bob can do his spreadsheets

While working on web applications, sometimes we come across a situation where we need to import a CSV or Excel file into the database. It’s a preferred way of importing large data in the database rather than entering it one by one. Adding large records programmatically saves a ton of time.

To accomplish such tasks, you need to write a program that can read data from spreadsheets. These records can then be inserted into the database.

PhpSpreadsheet is the library that helps you read the CSV or Excel file. The library provides support for reading and writing different types of file formats. Below is the screenshot of supported file formats.

File Supported

Before I came to know this library, I was using the fgetcsv method for reading the CSV file. And for the Excel files, I needed to convert Excel to CSV first and then read it using the fgetcsv() function.

PhpSpreadsheet simplifies this task for developers. Using PhpSpreadsheet, it is easier to handle the data from CSV and Excel files. Plus, you don’t need to convert Excel to CSV, the library directly reads the Excel file.

That being said, let’s take a look at how to read CSV and Excel files using PhpSpreadsheet.

Installation of PhpSpreadsheet Library

For the installation of this library, I recommend using Composer. Open the terminal in your project root directory and run the command:

composer require phpoffice/phpspreadsheet

In the next part of the tutorial, I am going to read CSV/Excel files and insert their data into the database. For this, I created dummy files that contain fake data as follows:

dummy-records

To store these records, I am creating a table ‘users’ in the database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 `company` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

For the sake of the tutorial, I am using the above dummy data. The user should change the table structure as per their dataset.

Next, create a config.php and add a code for database connection in it.

config.php

<?php
$db_host = 'DB_HOST';
$db_username = 'DB_USERNAME';
$db_password = 'DB_PASSWORD';
$db_name = 'DB_NAME';
 
$db = new mysqli($db_host, $db_username, $db_password, $db_name);
 
if($db->connect_error){
    die("Unable to connect database: " . $db->connect_error);
}

Make sure to replace the placeholders with the actual values.

Read CSV/Excel File in PHP

Let’s do the actual coding. First, create a form that will have a file input and submit button. The user uploads their CSV/Excel file and hits the submit button. On form submission, the entries of the uploaded file should be inserted into the ‘users’ table.

<form method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <p><button type="submit" name="submit">Submit</button></p>
</form>

Next, the code which will execute on the form submission will be as follows.

<?php
require_once 'vendor/autoload.php';
require_once 'config.php';
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetReaderCsv;
use PhpOfficePhpSpreadsheetReaderXlsx;
 
if (isset($_POST['submit'])) {
 
    $file_mimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
     
    if(isset($_FILES['file']['name']) && in_array($_FILES['file']['type'], $file_mimes)) {
     
        $arr_file = explode('.', $_FILES['file']['name']);
        $extension = end($arr_file);
     
        if('csv' == $extension) {
            $reader = new PhpOfficePhpSpreadsheetReaderCsv();
        } else {
            $reader = new PhpOfficePhpSpreadsheetReaderXlsx();
        }
 
        $spreadsheet = $reader->load($_FILES['file']['tmp_name']);
 
        $sheetData = $spreadsheet->getActiveSheet()->toArray();
 
        if (!empty($sheetData)) {
            for ($i=1; $i<count($sheetData); $i++) { //skipping first row
                $name = $sheetData[$i][0];
                $email = $sheetData[$i][1];
                $company = $sheetData[$i][2];

                $db->query("INSERT INTO USERS(name, email, company) VALUES('$name', '$email', '$company')");
            }
        }
        echo "Records inserted successfully.";
    } else {
        echo "Upload only CSV or Excel file.";
    }
}
?>

In the above code, I am finding the type of file whether it is CSV or Excel. And then I am reading the file using the functions provided for these file formats. You can read more about this on official documentation here.

I hope you understand how to read CSV and Excel files using PhpSpreadsheet. If you want to write to the spreadsheet then check out the article Exporting MySQL Database Data to Excel/CSV Using PHP.

Related Articles

  • How to Read and Write Spreadsheet Files in PHP
  • Upload Image using Bulletproof Library in PHP
  • IP Address Lookup using Abstract API and PHP

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Database applications written in php often need to export data for reporting purpose. A popular export format is excel. Excel is a spreadsheet that lays out data in a grid format. Excel itself is a microsoft proprietory format. There are many libraries available for php like Spreadsheet_Excel_Writer pear package etc that can do the job. However these libraries need to be included with the application and are sometimes difficult to install.

If only a simple export in grid format is needed, then there are better solutions than excel. For example csv and tsv. These are very simple formats that can be generated with just a little code and are compatible with most spreadsheet applications like openoffice or ms-excel. Lets take a look at each of these.

1. CSV — Comma separated value

Another very simple format is csv : comma separated values format which can be opened in applications like ms-excel and openoffice.org spreadsheet. Can be written like this :

$data = '"Name","City","Country"' . "n";
$data .= '"Ashok","New Delhi","India"' . "n";
$data .= '"Krishna","Bangalore","India"' . "n";

$f = fopen('data.csv' , 'wb');
fwrite($f , $data );
fclose($f);

Both the above mentioned methods are powerful ways of representing tabular data being output from a database. Both the formats are very portable. There are some more rules to how to write csv files in proper format and can be read at the wikipedia article on the subject

2. TSV — Tab Separated Value Format

$data = '"Name"t"City"t"Country"' . "n";
$data .= '"Ashok"t"New Delhi"t"India"' . "n";
$data .= '"Krishna"t"Bangalore"t"India"' . "n";

$f = fopen('data.xls' , 'wb');
fwrite($f , $data );
fclose($f);

In that above example we are writing tabular data or say data from a database table into a file line by line and field by field. Its very simple to understand and read and at the same time its very portable as an export. That was nothing more than a simple tab delimited file (tsv : tab separated values) which Ms-excel , openoffice are comfortable at reading. And yes open it in excel and save as any other format you want. The filename can be ‘data.tsv’ if you like.

Conclusion

The above mentioned formats have many benefits over closed formats like excel. These formats are standard, portable and widely supported. They can be used for import directly in databases like mysql.

Unless there is a need to create complex formatting and media embedding, csv/tsv format should work well. If you need to create xlsx files however, check out the php library called phpexcel from codeplex.

Dependencies

PHP >= 5.3

Installation

If you’re using Composer to manage libraries, include this package in your composer.json

"require" : {
    "faisalman/simple-excel-php" : "0.3.*"
}

If you want to try version 0.4 (still in develop branch) you can use

"require" : {
    "faisalman/simple-excel-php" : "develop as 0.4.0-alpha"
}

Or just load this library in your PHP project by including SimpleExcel.php

require_once('../your/project/directory/here/lib/SimpleExcel/SimpleExcel.php');

Usage Example

Prior version 0.4


use SimpleExcelSimpleExcel;

$excel = new SimpleExcel('CSV');
$excel->parser->loadFile('test.csv');

echo $excel->parser->getCell(1, 1);

$excel->convertTo('JSON');
$excel->writer->addRow(array('add', 'another', 'row'));
$excel->writer->saveFile('example');

Version 0.4

Get specific content from CSV file


use SimpleExcelSimpleExcel;

$excel = new SimpleExcel();
$excel->loadFile('/home/faisalman/Downloads/test.csv', 'CSV');  // Load CSV file

print_r($excel->getWorksheet(1));                   // get array of all cells from worksheet 1
print_r($excel->getWorksheet(1)->getColumn(2));     // get array of cells in column 2 from worksheet 1
print_r($excel->getWorksheet(1)->getRecord(3));        // get array of cells in row 3 from worksheet 1
print_r($excel->getWorksheet(1)->getCell(1, 2));    // get specific cell in row 1 column 2 from worksheet 1

Convert from HTML table to JSON


use SimpleExcelSimpleExcel;

$excel = new SimpleExcel();
$excel->loadFile('/home/faisalman/Downloads/test.html', 'HTML');                // Load HTML file from server

$excel->exportFile('/home/faisalman/Downloads/test.json', 'JSON');              // Save into a directory in running server
$excel->exportFile('php://output', 'JSON', array('filename' => 'test.json'));   // Save into client (browser download)

Load CSV with semicolon, export as CSV with comma


use SimpleExcelSimpleExcel;

$excel = new SimpleExcel();
$excel->loadFile('/home/faisalman/Downloads/test.csv', 'CSV', array('delimiter' => ';'));
$excel->exportFile('/home/faisalman/Downloads/test2.csv', 'CSV', array('delimiter' => ','));

Change some elements from XML file


use SimpleExcelSimpleExcel;
use SimpleExcelSpreadsheetWorksheet;

$excel = new SimpleExcel();
$excel->loadFile('/home/faisalman/Downloads/test.xml', 'XML');              // Load XML file which contains 3 worksheets

$excel->getWorksheet(1)->setRecord(9, array('9', 'Kota Bandung', '3'));     // Update row 9 in worksheet 1
$excel->getWorksheet(1)->removeRecord(2);                                   // Delete row 2 from worksheet 1

$excel->insertWorksheet(new Worksheet());                                   // Insert a new worksheet
$excel->getWorksheet(4)->insertRecord(array('ID', 'Nama Kota', 'Kode'));    // Insert a new row to worksheet 4

$excel->exportFile('/home/faisalman/Downloads/test2.xml', 'XML');           // Write document as another XML file

Write a new XML file


use SimpleExcelSimpleExcel;
use SimpleExcelSpreadsheetWorksheet;

$worksheet = new Worksheet();                                       // Define a new worksheet
$worksheet->insertRecord(array('ID', 'Nama Kota', 'Kode'));

$excel = new SimpleExcel();
$excel->insertWorksheet($worksheet);                                // Insert defined worksheet to excel document
$excel->insertWorksheet(new Worksheet());                           // Insert a new blank worksheet
$excel->getWorksheet(2)->insertRecord(array('1', '2', '3'));        // Insert a new row to that blank worksheet

$excel->exportFile('/home/faisalman/Downloads/test.xml', 'XML');    // Write document as XML file

Documentation

  • v0.3
  • v0.4

Contributors

  • Faisal Salman
  • Cristobal Dabed
  • Moritz Kröger
  • Will Jaspers

License

Copyright (c) 2011-2013 Faisalman <fyzlman@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the «Software»), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Like this post? Please share to your friends:
  • Php excel to pdf converter
  • Php excel spreadsheet excel writer
  • Php excel spreadsheet excel reader
  • Php excel read excel file
  • Php excel parser что это