2017-03-24 1 views
0

PHP를 사용하여 MySQL 쿼리 결과를 파일에 쓰는 데 문제가 있습니다. 검색 결과가 분명히 나오며 파일이 만들어 지지만 파일을 열면 파일이 비어 있습니다. 나는 그것이 파일에 쓰는 방법과 관련이 있다고 생각하지만 확실하지 않습니다.PHP로 MySQL 쿼리 결과를 CSV 파일로 출력

$result = mysql_query($compsel); 
if(!result) die("unable to process query: " . mysql_error()); 
$fp = fopen('results.csv','w'); 
mysql_data_seek($result,0); //set data pointer to 0 
$rw = mysql_fetch_array($result, MYSQL_ASSOC); 
print_r($rw); 
foreach ($rw as $fields){ 
    fputcsv($fp, $fields); 
} 
fclose($fp); 

미리 감사드립니다.

답변

1

다음은 예입니다 :

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

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

// output the column headings 
fputcsv($output, array('Column 1', 'Column 2', 'Column 3')); 

// fetch the data 
mysql_connect('localhost', 'username', 'password'); 
mysql_select_db('database'); 
$rows = mysql_query('SELECT field1,field2,field3 FROM table'); 

// loop over the rows, outputting them 
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row); 

당신은 당신의 필요에 따라 수정할 수 있습니다. 출처 : http://code.stephenmorley.org/php/creating-downloadable-csv-files/

+0

정말 고마워. – KittenMittons