0

我需要在我的应用程序中将 db 内容导出为 csv 文件。它正在工作。但是内容不是从第一行开始的。它从第 40 行开始。我还需要做什么?

header('Content-Encoding: UTF-8');
header("Cache-Control: cache, must-revalidate");
header("Pragma: public");
header('Content-Type: text/csv, charset=UTF-8; encoding=UTF-8');
$filename = date('Y_m_d_s');
header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");

if($dbResult) {
    $cnthead=0; $cntr =count($dbResult[0])-1;
    foreach($dbResult[0] as $key => $Val){ 
        echo $key;
        if($cnthead < $cntr) {
            echo ",";
            $cnthead++;
        }
    }
    echo "\n";
    foreach($dbResult as $dbRes){
        $cntcontnt=0;
        foreach($dbRes as $dbVal){ 
            echo $dbVal; 
            if($cntcontnt < $cntr) {
                echo ",";
                $cntcontnt++;
            }
        }
        echo "\n";
    }
}

$dbResult 数组如下所示,

Array
(
    [0] => Array
        (
            [Appraisee Name] => aaa R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => vvv A
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )

    [1] => Array
        (
            [Appraisee Name] => gan R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => fcv R
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        ) 
)
4

3 回答 3

1

我在最上面的问题上有空行。我添加了 ob_end_clean(); 在写入文件之前,问题是 res

于 2019-04-02T11:20:12.010 回答
0

我想问题从这里开始

$cntr =count($dbResult[0])-1; //so $cntr = 7;

foreach($dbResult[0] as $key => $Val){ 
    echo $key;
    if($cnthead < $cntr) {//this condition only true for first 7 loops after it will fails
        echo ",";
        $cnthead++;
    }
}

例如,$dbResult 有超过 7 条记录,它不会进入第一个 forloop if 语句。如果你想循环 $dbResult 所有记录然后更改你的代码如下。

我想你需要改变

$cntr =count($dbResult[0])-1;

进入

$cntr =count($dbResult)-1;

在您的代码中尝试此更改

于 2013-08-23T07:02:06.377 回答
0

感谢user2063756,您为我指明了正确的方向。我的 CSV 文件从第 4 行开始。仅仅因为我使用的是我的常量的 PHP 包含文件....并且该文件在“

曾是 ”

代替 ”

于 2017-03-30T15:32:37.430 回答