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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测