-1

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
Mike
  • 1,853
  • 3
  • 45
  • 75
  • 2
    Define "not working". Any error messages, warnings, notices? What'd you get vs what you expect? etc. If your error_reporting setting isn't set to E_ALL at least, fix that first. – cHao Jan 25 '17 at 14:54
  • It'd also be helpful to create an MVCE. A problem regarding `fgetvsv()` doens't need SQL or messing with HTTP headers. – HPierce Jan 25 '17 at 14:58
  • @cHao There are no errors, it just exports a blank file. That's why Om confused. If there was an error I'd have something to chase down, but the file is just blank and I can `echo` or `print_r` to is so I know that it gets opened. Just the `fputcsv` seems to not be working. – Mike Jan 25 '17 at 14:58
  • Start debugging your code. Does your query returning any data? If you put a `die('entering while');` after your `while` statement, your code reaches that part? – Felippe Duarte Jan 25 '17 at 15:00
  • Have you tried to print_r() the data to be sure it's not null? Also you could use and incremental variable to check how many times it's running. If it's running as much as you want but no data is shown then something is wrong with the data. – Antonios Tsimourtos Jan 25 '17 at 15:01
  • @FelippeDuarte I have done some debugging. The query that I'm testing this with return 7600 rows with 72 columns. I'll try that `die` though hadn't thought of that. – Mike Jan 25 '17 at 15:02
  • @AntonisTsimourtos the query works and the data is there. If I put a `print_r` after the `fputcsv($openFile, $modRow, ',','"')` it prints the arrays that hold the data, but the `fputcsv` doesn't add the rows. – Mike Jan 25 '17 at 15:06
  • Could you please try instead of `$modRow` to insert `"hi"` and tell me the results? Also, a good library to check it [out](https://phpexcel.codeplex.com/) . Have never seen `ini_set('display_errors', 'On');` - does it work? Otherwise try `ini_set('display_errors', 1);` – Antonios Tsimourtos Jan 25 '17 at 15:37
  • @AntonisTsimourtos when I try `fputcsv($openFile, 'Hi', ',','"');` it throws an error about a string supplied when an array is expected. As for the `ini_set('display_errors', 'On');`, yes that works, I get errors all too often. – Mike Jan 25 '17 at 15:47
  • @AntonisTsimourtos I tried creating an array `$Test[] = ('Test'=>'testII','testI'=>'TestIII');` and using it `fputcsv($openFile, $Test, ',','"');`, but no the browser goes to a blank page and there is not download. Nevermind I realized I created the Array wrong. I did this to fix it `$Test = array('Test'=>'testII','testI'=>'TestIII');`. but now the file is blank. – Mike Jan 25 '17 at 15:49
  • Are there any other calls after closing the file? Redirecting or something like that? Also try to change `$openFile = fopen($filepath . $filename,'w');` to `$openFile = fopen($filepath . $filename,'a');` – Antonios Tsimourtos Jan 25 '17 at 15:52
  • @AntonisTsimourtos No, the `fclose($openFile);` is the last line in the file. – Mike Jan 25 '17 at 15:53
  • Edited above comment, also i don't quite understand why you set `$headers = NULL;` but i am just asking to be sure that you know what it does. – Antonios Tsimourtos Jan 25 '17 at 15:56
  • @AntonisTsimourtos changing to 'a' still gives me a blank file. – Mike Jan 25 '17 at 15:56
  • @AntonisTsimourtos I use that so that the headers are only printed once, or would be if the `fputcsv` was working. Once the `$headers` is set it won't go into that `if` again to reset them and reprint them. – Mike Jan 25 '17 at 15:57
  • Ok, i can suggest two things. First try with `a+` . Secondly, remove the query and try to create a csv file with simple lines. After you see you have some results then start adding code. It is slow but this way you are going to find the problem i guess. Can't think something else for now.. – Antonios Tsimourtos Jan 25 '17 at 16:00

1 Answers1

0

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"

Mike
  • 1,853
  • 3
  • 45
  • 75