2017-12-29 32 views
1

php 페이지는 브라우저에서 자동으로 다운로드되는 CSV 파일을 생성합니다. 샘플 데이터가 포함 된 버전입니다.php 및 ajax로 CSV 파일 생성 및 다운로드

<?php 

$cars = array(
    array("Volvo",22,18), 
    array("BMW",15,13), 
    array("Saab",5,2), 
    array("Land Rover",17,15) 
); 

// output headers so that the file is downloaded rather than displayed 
header('Content-Type: text/csv; charset=utf-8'); 
header('Content-Disposition: attachment; filename=csvfile.csv'); 

// create a file pointer connected to the output stream 
$output = fopen('php://output', 'w'); 

// output the column headings 
fputcsv($output, array('Car', 'Year', 'Miles')); 

//Loop through the array and add to the csv 
foreach ($cars as $row) { 
    fputcsv($output, $row); 
} 

?> 

나는 사용자가 생성 할 수 있도록 ajax를 사용하여 다른 페이지에서이 작업을 실행할 수 있도록하고 싶습니다/메인 페이지를 떠나지 않고 csv을 다운로드 할 수 있습니다. 메인 페이지에서 사용중인 JavaScript입니다. 내 실제 페이지에서 나는 아약스를 통해 오는 데이터를 사용하고있다.

$('button[name="exportCSVButton"]').on('click', function() { 
    console.log('click'); 
    $.ajax({ 
     url: 'exportCSV.php', 
     type: 'post', 
     dataType: 'html', 
     data: { 

      Year: $('input[name="exportYear"]').val() 
     }, 
     success: function(data) { 
      var result = data 
      console.log(result); 


     } 
    }); 
}); 

내가 스크립트를 실행 버튼을 클릭

, 그것은 실행 대신 저장/다운로드 csv으로는 콘솔에 전체 일을 인쇄합니다. 내가 원하는 것을 성취 할 수있는 방법이 있습니까? 실제로 파일을 서버에 저장하고 다시 열지 않아도됩니다.

+0

가능한 중복 : https://stackoverflow.com/q/16086162/2732506 – Alexey

+0

왜 당신이를 위해 아약스를해야합니까? 서버 쪽 브라우저에 적절한 헤더를 넣으면 다운로드를 위해 리디렉션되지 않습니다. – charlietfl

+0

@charlietfl 아마도 그렇지 않습니다. 나는 눌렀을 때 PHP 스크립트를 실행하고 결과를 내보내는 버튼이있는 메인 페이지가 있습니다. 대안은 무엇입니까? – blackandorangecat

답변

0

숨겨진 iframe을 작성하고 JavaScript를 통해 iframe의 소스가 exportCSV.php가 수행하는대로 적절한 헤더와 데이터를 보낸 PHP 파일로 설정되었습니다.

그러나,이 아이디어를 좋아하지 않는 경우에, 당신을 console.log (결과를) 교체 jQuery File Download 또는 FileSaver.js

0

같은 라이브러리를 사용할 수 있습니다; 파일 저장 코드. 여기를 확인 JavaScript: Create and save file

브라우저 대화 상자에서 파일을 저장하는 가장 좋은 방법은 간단한 코드를 사용하는 것입니다.

<a href="#" onclick="window.open('exportCSV.php?year=' + $('input[name="exportYear"]').val())" >Download File</a> 
+0

대신 복제물로 표시되어야하며 표절 할 가능성이 있습니다. –