-
-
Save manojiksula/2cab87175598ebef4ea7119eddfc99f4 to your computer and use it in GitHub Desktop.
Read an Excel sheet as PHP array. (Needs PHPExcel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Needs PHPExcel | |
// https://phpexcel.codeplex.com/ | |
function excel_to_array($inputFileName,$row_callback=null){ | |
if (!class_exists('PHPExcel')) return false; | |
try { | |
$inputFileType = PHPExcel_IOFactory::identify($inputFileName); | |
$objReader = PHPExcel_IOFactory::createReader($inputFileType); | |
$objPHPExcel = $objReader->load($inputFileName); | |
} catch(Exception $e) { | |
return ('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); | |
} | |
$sheet = $objPHPExcel->getSheet(0); | |
$highestRow = $sheet->getHighestRow(); | |
$highestColumn = $sheet->getHighestColumn(); | |
$keys = array(); | |
$results = array(); | |
if(is_callable($row_callback)){ | |
for ($row = 1; $row <= $highestRow; $row++){ | |
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,null,true,false); | |
if ($row === 1){ | |
$keys = $rowData[0]; | |
} else { | |
$record = array(); | |
foreach($rowData[0] as $pos=>$value) $record[$keys[$pos]] = $value; | |
$row_callback($record); | |
} | |
} | |
} else { | |
for ($row = 1; $row <= $highestRow; $row++){ | |
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,null,true,false); | |
if ($row === 1){ | |
$keys = $rowData[0]; | |
} else { | |
$record = array(); | |
foreach($rowData[0] as $pos=>$value) $record[$keys[$pos]] = $value; | |
$results[] = $record; | |
} | |
} | |
return $results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment