我正在尝试使用PHP导出CSV。但是,不是打印结果,而是在生成的CSV文件中打印Resource id #26
。如果我从末尾删除退出,则打印我的整个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);
}
答案 0 :(得分:2)
那是因为$ 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) );
答案 1 :(得分:0)
打开一大块可写内存:
$file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+'); // 128mb
写入...然后用以下内容获取内容:
rewind($file);
$output = stream_get_contents($file);
fclose($file);
答案 2 :(得分: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>";
}