dongqiaozhe5070 2017-02-17 13:22
浏览 33
已采纳

为什么我的fputcsv不工作?

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 = "
";   //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( "/|
/", "", $modRow );
    /*
    $modRow = str_replace('
', " ", $modRow);
    $modRow = str_replace('
', " ", $modRow);
    $modRow = str_replace('
', " ", $modRow);
    $modRow = str_replace('', " ", $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.

  • 写回答

2条回答 默认 最新

  • dotif64826 2017-02-17 14:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀