2012-11-23 73 views
0

我想用PHP导出CSV。但不是打印结果,而是在生成的CSV文件中打印Resource id #26。如果我从结尾中删除退出,它会打印出我的整个HTML页面内容。我的代码是...导出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); 
    } 
+0

'exit($ output);'应该按预期打印'资源ID#xx'。那么你的问题是什么? –

+0

我想虚拟地创建一个文件,编写它并提供它下载,以便文件不应该保存在服务器上。 – Sankalp

+1

像这样http://php.net/manual/en/function.fputcsv.php#106583? –

回答

1

这是因为$输出是一个资源,这是什么fopen()回报。您需要使用fread()来获取其内容。

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

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

而且,这也是一个好主意,让客户知道什么期望设置content-length头:

header('Content-Length: ' . strlen($csv_output)); 
+0

我想虚拟创建一个文件,编写并提供下载文件,使其不应保存在服务器上。 我想你没有得到我的问题。 – Sankalp

+0

让我知道我的编辑是否有帮助。 – SuitedSloth

0

打开可写存储器的块:

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

写它...然后用获取的内容

rewind($file); 
$output = stream_get_contents($file); 
fclose($file); 
+0

我完全不清楚您提供解决方案的链接。你可以重写吗?我的数据数组是('$ customerListAll') – Sankalp

+0

不,这是您的数据,我不需要知道数据结构。上面的代码显示了如何将文件资源打开到内存中的临时位置。一旦你有$文件,你可以用'fputcsv($ file,..fields ..)'写入它。写完所有信息后,使用rewind和stream_get_contents函数获取所述文件的内容。 –

+0

它正在写我的页面的HTML。 – Sankalp

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>"; 


}