Convert XLS to CSV in PHP

In Convert XLS to CSV tutorial, I have explained how to convert XLS to CSV in PHP using PHPExcel Library.

Convert XLS to CSV in PHP

Follow the below Steps to convert XLS to CSV.

Step 1). Download PHPExcel library from Github and extract it.

 

Step 2). Include PHPExcel.php in your file.

include 'PHPExcel/Classes/PHPExcel.php';

 

Step 3)  Open Excel file using PHPExcel IOFactory

$objReader = PHPExcel_IOFactory::createReader("Excel5");
//Excel5 is the type of excel file.

$objReader->setReadDataOnly(true);	
$objPHPExcel = $objReader->load("input.xls");

Supported File readers :
Excel5 -> file format between Excel Version 95 to 2003
Excel2003XML -> file format for Excel 2003
Excel2007 -> file format for Excel 2007

We can get file reader type automatically using

$fileType=PHPExcel_IOFactory::identify("input.xls");

 

Step 4) Create a CSV File Writer

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');

 

Step 5) Save XLS as CSV

$objWriter2007->save("output.csv");

Putting it All Together: Below is the function to convert XLS to CSV in PHP

<?php
require_once('PHPExcel/Classes/PHPExcel.php');

//Usage:
convertXLStoCSV('input.xls','output.csv');

function convertXLStoCSV($infile,$outfile)
{
	$fileType = PHPExcel_IOFactory::identify($infile);
	$objReader = PHPExcel_IOFactory::createReader($fileType);

	$objReader->setReadDataOnly(true);	
	$objPHPExcel = $objReader->load($infile);	

	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
	$objWriter->save($outfile);
}

?>

Note: You can use the same function to convert XLSX to CSV. You can  convert XLS to PDF, XLS to CSV , or XLS to HTML by  changing  the File reader and writer types.

Troubleshooting: Sometimes conversion fails due to memory issues.You can increase the memory limit, by adding the below line at the start of the file.

ini_set('memory_limit', '2000M'); //for 2GB

//For no limits
ini_set('memory_limit', -1);