Search code examples
phpfopenexport-to-csvfputcsv

php fputcsv not working


I do not understand why my fputcsv is not working. Here is what I've got:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    $id = $_GET['Id'];
    include('DBConn.php');
    $query = $conn->prepare('SELECT QName, tsql from pmdb.QDefs WHERE Id = ' . $id);
    $query->execute();
    $qdef = $query->fetch(PDO::FETCH_ASSOC);

    // Create and open file for writing
    $filepath = 'exports/';
    $filename = $qdef['QName'] . '.csv';
    //$filename = $qdef['QName'] . '.csv';
    try
    {
        $openFile = fopen($filepath . $filename,'w');
        header('Content-Encoding: UTF-8');
        header('Content-Type: text/csv; charset:UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    catch(Exception $e)
    {
        echo "Something went wrong<br>";
        die( print_r( $e->getMessage()));
    }

    // Use returned tsql field as query for dataset
    $tsql = $qdef['tsql'];
    //echo "tsql<br>"; print_r($tsql); //This was to make sure that I'm getting the correct query
    $query = $conn->prepare($tsql);
    $query->execute();

    // Output data to CSV file
    $headers = NULL;
    while ($row = $query->fetch(PDO::FETCH_ASSOC))
    {
        //Write column headings to file
        if (is_null($headers))
        {
            $headers = array_keys($row);

            if ($headers[0] == 'ID')
                $headers[0] = 'Id';
            fputcsv($openFile, $headers); //This is doing nothing The headers from here don't get printer to the file
            //print_r($headers); //This was to check and see if the headers exist
            print_r($openFile);echo ","; //This is to see what is returned from the fopen -> it returns "Resource is #4"
            foreach($headers as $Header)
            {
                echo $Header. ","; //This was to print the headers to see if I can write to the file. I can the headers print.
            }
        }
        //Write data
        $modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', $row);
        /*
        $modRow = str_replace('\r\n', " ", $modRow);
        $modRow = str_replace('\n\r', " ", $modRow);
        $modRow = str_replace('\n', " ", $modRow);
        $modRow = str_replace('\r', " ", $modRow);
        */
        fputcsv($openFile, $modRow, ',','"');//print_r($modRow); //The rows don't get added to the file from here like they should, but I also don't get any error.
    }

    // Close file
    fclose($openFile);

    //echo $filepath . $filename;
?>

There are no errors It just exports a blank file, though it does name it correctly. The file should have 30+ columns and 10000+ rows for most of the reports.

This is how my error reporting is set:

    error_reporting(E_ALL|E_STRICT);//For use in trouble shooting
    ini_set('display_errors', 'On');//For use in trouble shooting

Solution

  • I ended up creating a workaround since In cannot get the fputcsv to work.

    I'm now doing this:

    foreach($modRow as $RowPrint)
    {
        echo '"' .trim(unserialize(serialize($RowPrint))). '"' .$sep;
    }
    echo $br;
    

    Where $sep = "," and $br = "\r\n"