2013-06-24 4 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'); 

} 

은 $ 결과 변수는 여기에서 온다 : 곳에서도 찾기 시작하는

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

임은 확실하지 이것은 내가 가지고있는 코드입니다. 나는이 일을하는 다양한 방법으로 인터넷을 살펴본 후 그들 모두를 시험해 보았지만 아직도 제대로 작동하지 못했습니다. 제발 도와주세요!

고마워요은

+1

그럼 어떻게 될까요? 오류 메시지? 대신 파일이 브라우저에 표시됩니까? 파일이 다운로드되었지만 손상 되었습니까? – JJJ

+0

파일을 다운로드 할 때 Firefox를 사용할 때 Firebug를 사용하여 버튼에 어떤 오류가 발생하는지 확인하십시오. 500 Internal Server Error – MONZTAAA

답변

21

이후에 내용을 echo해야합니다.

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

echo $shtml; 

콘텐츠 유형 application/force-download는 어떻게 찾았습니까? 나는 그것에 대해 들어 본 적이 없다. CSV에 대한 적절한 MIME 타입 당신은 당신이 당신의 코드에서 그것을하지 않았다 당신이 필요로 또한 $shtml를 표시 php manual

에서 헤더 함수를 사용하는 방법을 더 많은 예제를 찾을 수 있습니다 텍스트/CSV

입니다.

+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);'는 헤더가 이미 전송되었다는 오류를 발생시킵니다. –