Why won't my fputcsv work?

断了今生、忘了曾经 提交于 2019-12-25 08:40:21

问题


I cannot get the PHP built-in function fputcsv() to work. Here is what I've tried:

error_reporting(E_ALL);
ini_set('display_errors', 1);

include('DBConn.php');              //My SQL server connection information
include 'Helper/LogReport.php';     //Keeps a count of how many times reports are exported


$query = $conn->query("SELECT QName, tsql from pmdb.QDefs WHERE QName = '" .$TableName. "'");
$query->execute();
$qdef = $query->fetch(PDO::FETCH_ASSOC);


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

//define separators
$sep = ",";     //separator
$br = "\r\n";   //line break

// Use returned tsql field as query for dataset
$tsql = $qdef['tsql'];
if(isset($DataReturn))
{
    if(strpos($DataReturn['Order'],'EDIT'))
    {
        $DataReturn['Order'] = str_replace('EDIT','Id',$DataReturn['Order']);
    }
    $tsql = $tsql . $DataReturn['WhereClause'] . $DataReturn['Order'] . $DataReturn['Limit'];
}

$query = $conn->query($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((array)$row);
        if ($headers[0] == 'ID')
            $headers[0] = 'Id';
        fputcsv($openFile, $headers, ',','"');

    }
    //Write data
    $modRow = preg_replace('/ \d{2}:\d{2}:\d{2}\.\d{3}/', '', array_values($row));
    $modRow = preg_replace( "/\r|\n/", "", $modRow );
    /*
    $modRow = str_replace('\r\n', " ", $modRow);
    $modRow = str_replace('\n\r', " ", $modRow);
    $modRow = str_replace('\n', " ", $modRow);
    $modRow = str_replace('\r', " ", $modRow);
    $modRow = str_replace(' ', " ", $modRow);
    $modRow = str_replace('Â ', " ", $modRow);
    $modRow = str_replace('"', '', $modRow);
    $modRow = str_replace("'", "", $modRow);
    */
    fputcsv($openFile, $modRow, ',','"');
}

// Close file
fclose($openFile);

But nothing gets printed to the file, it's just blank. Am I setting something up wrong?

EDIT

I have tried every variation for the fopen that I could find on this page, but they all give me a blank file when using fputcsv. I only get data in the file when I echo the arrays.

END OF EDIT

You can see the header array is setup from the array keys returned from the query to the DB. I can echo them and get the correct headers.

Then there are the rows of data themselves. I remove unwanted characters, but they are still arrays of data and should print with the fputcsv. Again I can echo the contents of the array by looping through it. That's how I've been getting the exports to work right now, but I know that is just a workaround and want to get the fputcsv working.

This is how I'm getting the rows printed:

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

UPDATE

Here's the output when I print_r the headers:

Array
(
    [0] => Id
    [1] => QSRC
    [2] => QNAME
    [3] => QDEF
    [4] => ISACTIVE
    [5] => RUNREPORT
    [6] => FILEPATH
    [7] => TSQL
)

and here's one line from when I print_r the $modRow:

Array
(
    [Id] => 60
    [QSRC] => bau
    [QNAME] => Oops I deleted this!
    [QDEF] => SELECT REGION
    [ISACTIVE] => 0
    [RUNREPORT] => 0
    [FILEPATH] => 
    [TSQL] => 
)

I print_r both after the fputcsv should have printed them into the file. These are the only things in the file.


回答1:


I removed my first answer, as it was incorrect.

*******************EDIT*******************

You need to add this to the end of your file:

exit();

This tells the browser you are finished writing to the file and ensures no extra content is sent to the browser for security reasons.




回答2:


You cannot use php://stdout to send output to the browser. You could use php://memory instead to store the string and then read it back.

$fd = fopen('php://memory','rw');
fwrite($fd, 'hey there'); //This would be your fputcsv stuff
fseek($fd, 0); //Reset the file pointer
$content = fread($fd, 4096); //This will read 4096 bytes maximum
echo $content;


来源:https://stackoverflow.com/questions/42299078/why-wont-my-fputcsv-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!