0

我正在尝试使用 PHP 导出 CSV。但不是打印结果,而是Resource id #26在生成的 CSV 文件中打印。如果我从末尾删除退出,它将打印我的整个 HTML 页面内容。我的代码是...

      if (isset($_REQUEST['download']) && ($_REQUEST['download'] == "yes")) {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=link_point_report.csv');
            $output = fopen('php://memory', 'w+');
            fputcsv($output, array('Member Id', 'Customer Name', 'Customer Email'));

            $customerListAll = $oAdmFun->linkpoint_check_customer('', '');       
             $oAdmFun->pr($customerListAll, true);
//                if (count($customerListAll) > 0) {
//                        for ($c = 0; $c < count($customerListAll); $c++) {
//                                fputcsv($output, array('Sankalp', 'Sankalp', 'Sankalp'));
//                        }
//                }

            ob_clean();
            flush();
            exit($output);
    }
4

3 回答 3

3

那是因为 $output 是一种资源,这是fopen()返回的。您需要使用fread()来获取其内容。

编辑:现在我明白你在问什么。要输出 CSV 的内容,您需要从资源中获取文本输出:

rewind( $output );
$csv_output = stream_get_contents( $output );
fclose( $output );
die( $csv_output );

设置content-length标头也是一个好主意,以便客户端知道会发生什么:

header('Content-Length: ' . strlen($csv_output) );
于 2012-11-23T17:10:09.963 回答
0

打开一块可写内存:

$file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+'); // 128mb

写入它...然后使用以下命令获取内容:

rewind($file);
$output = stream_get_contents($file);
fclose($file);
于 2012-11-23T18:06:14.773 回答
0
function CSV_HtmlTable($csvFileName)
{
// better to open new webpage 
echo "<html>\n<body>\n\t<table style=''>\n\n";
$f = fopen($csvFileName, "r");
$trcount = 0; //start the row count as 0
while (($line = fgetcsv($f)) !== false) {
        $trclass = ''; if ($trcount%2==0) { $trclass=' class="dark"'; } //default to nothing, but if it's even apply a class
        echo "\t\t<tr".$trclass.">\n"; //same as before, but now this also has the variable $class to setup a class if needed
        $tdcount = 0; //reset to 0 for each inner loop
        foreach ($line as $cell) {
                $tdclass = ''; if ($tdcount%2==0) { $tdclass=' class="dark"'; } //default to nothing, but if it's even apply a class
                echo "\t\t\t<td ".$tdclass."style='padding:.4em;'>" . htmlspecialchars($cell) . "</td>"; //same as before, but now this also has the variable $class to setup a class if needed
                $tdcount++; //go up one each loop
        }
        echo "\r</tr>\n";
        $trcount++; //go up one each loop
}
fclose($f);
echo "\n\t</table>\n</body>\n</html>";


}
于 2015-03-12T07:05:59.863 回答