Is it possible to import each line of an XLSX file to a row in a PHP array?
PHP provides a library to deal with Excel files. It is called PHP Excel library. It enables you to read and write spreadsheets in various formats including csv, xls, ods, and xlsx. You will need to ensure that you have PHP's upgraded version not older than PHP 5.2 .
You can use PHPExcel which is available here: https://phpexcel.codeplex.com/releases/view/119187
Here is what I use to read either xls
or xlsx
to an array:
require_once('/path/to/PHPExcel.php');
$filename = "example.xlsx";
$type = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($type);
$objPHPExcel = $objReader->load($filename);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheets[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($worksheets);
UPDATE / 2022-02-13:
PhpSpreadsheet has been available for a few years now and has replaced PHPExcel. The following code is more or less the same as above with a couple small improvements:
/**
* Create a multidimensional array of worksheets from a filename.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
*
* @return array
*/
function spreadsheet_to_array($nullValue = null, $calculateFormulas = true, $formatData = false) {
$results = [];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$results[$worksheet->getTitle()] = $worksheet->toArray($nullValue, $calculateFormulas, $formatData);
}
// save memory
$spreadsheet->__destruct();
$spreadsheet = NULL;
unset($spreadsheet);
return $results;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With