【问题标题】:Force Download CSV File强制下载 CSV 文件
【发布时间】:2013-06-20 14:40:05
【问题描述】:

我正在尝试创建一个强制下载 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;
}

我什至不确定从哪里开始寻找。我已经在互联网上查看了执行此操作的各种方法并尝试了所有方法,但仍然无法使其正常工作。请帮帮我!

-谢谢

【问题讨论】:

  • 那么会发生什么呢?错误信息?文件是否显示在浏览器中?文件是否下载但损坏?
  • 文件没有下载,例如当我使用 Firefox 并使用 Firebug 查看按钮是什么时,我收到此错误:500 Internal Server Error

标签: php csv


【解决方案1】:

将此代码放在循环下方。

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

echo $shtml;

您是如何找到内容类型 application/force-download 的?我从来没听说过。 CSV 的正确 MIME 类型是 text/csv

您可以在php manual中找到更多如何使用标头函数的示例

您还需要在代码中显示 $shtml 您没有这样做。

【讨论】:

  • 您的意思是将标题放在 for 之后或 $shtml = $shtml.$result[$i].. 之后? -谢谢
  • 标题应该在任何其他数据发送到浏览器之前发送。即使是白色字符也可以破坏脚本。
【解决方案2】:

嗯。你可以试试这个,如果你的结果不为空就可以了

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);
}

【讨论】:

  • header( 'Content-Length: '.$contLength); 将引发标头已发送的错误。
【解决方案3】:

你需要在标题后echo你的内容

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

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 2011-08-28
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    相关资源
    最近更新 更多