Saturday, February 5, 2022

[SOLVED] PHP export mysql data to Excel crontab linux

Issue

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...

<?php  
//export.php  
$connect = mysqli_connect("localhost", "user", "pw", "bd");
$output = '';
if(isset($_POST["export"]))
{
    $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>  
                    </tr>';
        while($row = mysqli_fetch_array($result))
        {
            $output .= '
                    <tr>  
                       <td align="center">'.$row["FamilyName"].'</td>  
                       <td align="center">'.$row["FirstName"].'</td>  
                    </tr>';
        }
        $output .= '</table>';
        header('Content-Type: application/xls');
        header("Content-Type: application/force-download");
        header('Content-Disposition: attachment; filename=assets_colaboradores.xls');
        //
        echo $output;
    }
}
?>

Solution

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);
    }
    exit();
}


Answered By - Daniel G
Answer Checked By - Marilyn (WPSolving Volunteer)