0

I'm exporting data from php array to xls file. Everything works great if I'm just writing them into file with echo like this:

function toExcel($arrayOfData) {
    $data = null;
    $rowCounter = 0;

    if(is_array($arrayOfData) === true) {
        foreach($arrayOfData as $key=>$value) {
            $colCounter = 0;
            if($key == 0) {
                foreach(array_keys($arrayOfData[0]) as $hKey => $header) {
                    echo xlsWriteLabel(0, $hKey, $header);
                }
                $rowCounter++;
            }
            if(is_array($value) === true) {
                foreach($value as $data) {
                    echo xlsWriteLabel($rowCounter, $colCounter, $data);;
                    $colCounter++;
                }
                $rowCounter++;
            }
        }
    }
 }

but what I want is just return a binary code in one variable like:

function toExcel($arrayOfData) {
    $data = null;
    $rowCounter = 0;

    if(is_array($arrayOfData) === true) {
        foreach($arrayOfData as $key=>$value) {
            $colCounter = 0;
            if($key == 0) {
                foreach(array_keys($arrayOfData[0]) as $hKey => $header) {
                    $data .= xlsWriteLabel(0, $hKey, $header);
                }
                $rowCounter++;
            }
            if(is_array($value) === true) {
                foreach($value as $data) {
                    $data .= xlsWriteLabel($rowCounter, $colCounter, $data);
                    $colCounter++;
                }
                $rowCounter++;
            }
        }
    }
  return $data;
}

When I do this, and then do echo toExcel($somearray); it will create xls that is broken.

Any idea why and how to fix it? I have other functions for start and end of xls file, so the problem is not there if anyone would think.

Michal Takáč
  • 1,005
  • 3
  • 17
  • 37

1 Answers1

1

Ok, so I figured out, there was a problem with scope, it should look like:

function toExcel($arrayOfData) {
$data = xlsBOF();
$rowCounter = 0;

if(is_array($arrayOfData) === true) {
    foreach($arrayOfData as $key=>$value) {
        $colCounter = 0;
        if($key == 0) {
            foreach(array_keys($arrayOfData[0]) as $hKey => $header) {
                $data .= xlsWriteLabel(0, $hKey, $header);
            }
            $rowCounter++;
        }
        if(is_array($value) === true) {
            foreach($value as $val) {
                $data .= xlsWriteLabel($rowCounter, $colCounter, $val);
                $colCounter++;
            }
            $rowCounter++;
        }
    }
}
$data .= xlsEOF();
return $data;

}
Michal Takáč
  • 1,005
  • 3
  • 17
  • 37
  • Did the original code echo `xlsBOF()` and `XLSEOF()` around the call to `toExcel()`? – Barmar Mar 02 '15 at 23:12
  • I don't remember anymore, sorry for that. But I'm sure you will be able to find it online, since those functions were taken from some blog. – Michal Takáč Apr 10 '15 at 07:22