Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

php - Force Download CSV File

I am trying to create a button that will force a CSV file download but for some reason I am not able to get it working. This is the code that I have:

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

}

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

}

The $result variable comes from here:

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

Im not sure even where to start looking. I have look over the internet on various ways of doing this and tried all of them and still can't manage to get it working. Please help me out!

-Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Put this code below your loop.

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

echo $shtml;

How did you find out the content type application/force-download? I've never heard of it. The proper MIME type for CSV is text/csv

You can find more examples how to use header function in php manual

You need also display $shtml you didn't do it in your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...