PHP를 통해 CSV로 쿼리 결과를 내보내십시오
-
10-07-2019 - |
문제
$ query라는 변수에 쿼리를 저장했다고 가정 해 봅시다. 결과 페이지에서 "CSV로 내보내기"라는 작은 하이퍼 링크를 만들고 싶습니다. 어떻게해야합니까?
해결책
$query = "SELECT * FROM table_name";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
다른 팁
어?
<a href="yourexport.php" title="export as csv">Export as CSV</a>
그리고 스크립트를 찾고 있다면 wich는 이것을 할 수 있습니다.
$myArray = array ();
$fp = fopen('export.csv', 'w');
foreach ($myArray as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
CSV = 쉼표 분리 된 값 = 쉼표로 값을 분리합니다.
쉼표 (,)로 분리 된 결과를 라인별로 에코 / 인쇄해야합니다.
귀하의 $ query가 귀하의 쿼리의 결과 집합이라고 가정합니다. 이는 연관 배열입니다.
while($query = mysql_fetch_assoc($rs)) {
// loop till the end of records
echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}
여기서 $ rs는 리소스 핸들입니다.
브라우저가 다운로드 상자를 팝업하도록하려면 파일 시작시 헤더를 설정해야합니다 (파일 이름이 Export.csv라고 가정) :
header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");
그게 다야!
추신이 메소드는 서버에 실제 파일을 남기지 않습니다. 서버에서 파일을 생성하려는 경우 기존 Fopen 및 Fwrite 기능을 사용하십시오.
제휴하지 않습니다 StackOverflow