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条)

报告相同问题?

悬赏问题

  • ¥20 基于Simulink的ZPW2000轨道电路仿真
  • ¥15 pycharm找不到在环境装好的opencv-python
  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题