I cannot find anything in phpExcel documentation. What I would like is to end up with an associative array with keys from the first row in the excel worksheet. It's something that can be done of course, but is there a native method?

Edited by PerplexedB: typo

3 Years
Discussion Span
Last Post by Martin_10

is there a native method?

I don't think so. I think you'll have to loop through your columns and rows and create the array from there.


I came up with something like this:

function readastable($sheet){
  $titles = $sheet->rangeToArray('A1:' . $sheet->getHighestColumn() ."1");
  // var_dump($titles);
  $boddy = $sheet->rangeToArray('A2:' . $sheet->getHighestColumn() .$sheet->getHighestRow());

Is there a way to get an associative array (say $table) a bit similar to what pdo would return like for a db query, without going through an iteration?


This will read an "orthogonal" worksheet into an array converting each row of the sheet into an associative array where the keys correspond to the title of the worksheet.

function readastable($sheet) {
  $highestrow = $sheet->getHighestRow();
  $highestcolumn = $sheet->getHighestColumn();
  $columncount = PHPExcel_Cell::columnIndexFromString($highestcolumn);
  $titles = $sheet->rangeToArray('A1:' . $highestcolumn . "1");
  $boddy = $sheet->rangeToArray('A2:' . $highestcolumn . $highestrow);
  $table = array();
  for ($row = 0; $row <= $highestrow - 2; $row++) {
    $a = array();
    for ($column = 0; $column <= $columncount - 1; $column++) {
      $a[$titles[0][$column]] = $boddy[$row][$column];
    $table[$row] = $a;
  return $table;

Can you show the way, to get the sheet of a xlsx document to give it to the function, please?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.