PHP export mysql data to Excel crontab linux

So, I have this code to export data from mysql database to an excel file and I want it to run with crobjob, the problem is that this code isn't extracting any values, it just gives me an empty scrren i don't know why...

$connect = mysqli_connect("localhost", "user", "pw", "bd");
$output = '';
    $query = "SELECT * FROM PersonalData ";
    $result = mysqli_query($connect, $query);
    if(mysqli_num_rows($result) > 0)
        $output .= '
            <table class="table" bordered="1">  
                    <tr align="center">  
                        <th align="center">Family Name</th>  
                        <th align="center">First Name</th>  
        while($row = mysqli_fetch_array($result))
            $output .= '
                       <td align="center">'.$row["FamilyName"].'</td>  
                       <td align="center">'.$row["FirstName"].'</td>  
        $output .= '</table>';
        header('Content-Type: application/xls');
        header("Content-Type: application/force-download");
        header('Content-Disposition: attachment; filename=assets_colaboradores.xls');
        echo $output;

1 answer

  • answered 2019-03-13 19:05 Daniel G

    Try outputting to CSV. Here's a function that converts an associative array to CSV that I built:

    function array2CSV($fileName, $array, $headers = false) {
        // Set file headers
        header('Content-type: text/csv');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Pragma: no-cache');
        header('Expires: 0');
        // Open CSV to write
        $file = fopen('php://output', 'w');
        // Assign header names either from $headers or the array keys of $array
        $headers = ($headers) ? $headers : array_keys($array[0]);
        // Write the header row into the file
        fputcsv($file, $headers);
        foreach ($array as $row) {
            // Write a row to the file
            fputcsv($file, $row);