Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created April 3, 2014 16:43
Show Gist options
  • Save lastguest/9958151 to your computer and use it in GitHub Desktop.
Save lastguest/9958151 to your computer and use it in GitHub Desktop.
Read an Excel sheet as PHP array. (Needs PHPExcel)
<?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