<?php
session_start();

if (empty($_SESSION['excel_report'])) {
    die('No data to export');
}

$report = $_SESSION['excel_report'];

function filterData(&$str) {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if (strpos($str, '"') !== false) {
        $str = '"' . str_replace('"', '""', $str) . '"';
    }
}

$fileName = "service-upload-data-report.xls";

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Pragma: no-cache");
header("Expires: 0");

$flag = false;

foreach ($report as $row) {
    if (!$flag) {
        echo implode("\t", array_keys($row)) . "\n";
        $flag = true;
    }
    array_walk($row, 'filterData');
    echo implode("\t", array_values($row)) . "\n";
}

unset($_SESSION['excel_report']);
exit;
