2013-06-24 86 views
11

我正在尝试创建一个按钮,该按钮将强制执行CSV文件下载,但由于某种原因,我无法使其工作。这是我的代码:强制下载CSV文件

public function export_to_csv($result) { 

$shtml=""; 

for ($i=0; $i<count($result); $i++){ 

$shtml = $shtml.$result[$i]["order_number"]. "," .$result[$i]["first_name"]. "," .$result[$i]["middle_name"]. "," .$result[$i]["last_name"]. "," .$result[$i]["email"]. "," .$result[$i]["shipment_name"]. "," .$result[$i]["payment_name"]. "," .$result[$i]["created_on"]. "," .$result[$i]["modified_on"]. "," .$result[$i]["order_status"]. "," .$result[$i]["order_total"]. "," .$result[$i]["virtuemart_order_id"]. "\n"; 

} 

Header('Content-Description: File Transfer'); 
Header('Content-Type: application/force-download'); 
Header('Content-Disposition: attachment; filename=pedidos.csv'); 

} 

$ result变量来自这里:

public function get_orders_k() { 

$db=JFactory::getDBO(); 

    $query = " select o.order_number, o.virtuemart_order_id, o.order_total, o.order_status, o.created_on, o.modified_on, u.first_name,u.middle_name,u.last_name " 
    .',u.email, pm.payment_name, vsxlang.shipment_name ' . 
    $from = $this->getOrdersListQuery(); 

$db->setQuery($query); 

$result=$db->loadAssocList(); 

    if ($result > 0) 
    { 
     $datos = VirtueMartModelKiala::export_to_csv($result); 

    }else return 0; 
} 

林不知道,甚至从哪里开始寻找。我已经通过各种方式浏览了互联网,并尝试了所有这些方法,但仍然无法实现其工作。请帮助我!

-Thanks

+1

那么会发生什么呢?错误讯息?该文件是否在浏览器中显示?文件是否下载但被破坏? – JJJ

+0

该文件没有下载,当我使用Firefox例如并使用Firebug来查看按钮的功能时,出现以下错误:500内部服务器错误 – MONZTAAA

回答

21

将这个代码的循环下方后echo内容。

header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="pedidos.csv"'); 

echo $shtml; 

你是如何找出内容类型application/force-download的?我从来没听说过。正确的MIME类型CSV是文本/ CSV

你可以找到更多的例子来说明如何使用头功能php manual

您还需要显示$shtml你没有做到这一点在你的代码。

+0

您的意思是将标题放在$ shtml = $ shtml之后或之后。 $ result [$ i] ..? - 感谢 – MONZTAAA

+2

在将任何其他数据发送到浏览器之前应该发送标题。即使白色字符也可以打破剧本。 – Robert

2

您需要的头

header('Content-Description: File Transfer'); 
header('Content-Type: application/force-download'); 
header('Content-Disposition: attachment; filename=pedidos.csv'); 
echo $shtml 
4

好吧。你可以试试这个,如果你的结果不是空的,它会起作用

public function export_to_csv($result) 
{ 
    if(!$result) return false; 
    ob_end_clean(); 
    header('Content-Type: text/csv'); 
    header('Content-Disposition: attachment;filename=pedidos.csv'); 
    $fp = fopen('php://output', 'w'); 
    $headrow = $result[0]; 
    fputcsv($fp, array_keys($headrow)); 
    foreach ($result as $data) { 
     fputcsv($fp, $data); 
    } 
    fclose($fp); 
    $contLength = ob_get_length(); 
    header('Content-Length: '.$contLength); 
} 
+0

'header('Content-Length:'。$ contLength);'会引发一个头文件已经发送的错误。 –