我正在尝试创建一个强制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
答案 0 :(得分:32)
将此代码放在循环下方。
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="pedidos.csv"');
echo $shtml;
您是如何找到内容类型应用程序/强制下载的?我从来没有听说过。 CSV的正确MIME类型为 text / csv
您可以在php manual
中找到有关如何使用标题功能的更多示例您还需要在代码中显示$shtml
。
答案 1 :(得分: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);
}
答案 2 :(得分:3)
您需要在标题
后echo
内容header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename=pedidos.csv');
echo $shtml
{{1}}