PHP를 통해 CSV로 내보내기
데이터베이스가 있다고 가정 해 봅시다 ... PHP를 통해 데이터베이스의 파일을 CSV 파일 (및 가능한 경우 텍스트 파일)로 내보낼 수있는 방법이 있습니까?
개인적으로이 기능을 사용하여 모든 배열에서 CSV 컨텐츠를 만듭니다.
function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
그런 다음 사용자가 다음과 같은 방법으로 해당 파일을 다운로드하도록 할 수 있습니다.
function download_send_headers($filename) {
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
사용 예 :
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();
이 명령을 사용하여 날짜를 내보낼 수 있습니다.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
먼저 mysql 서버에서 배열로 데이터를로드해야합니다.
그냥 기록을 위해, 연결은 waaaaaay 빠른 (나는 그것을 의미)보다 fputcsv
, 심지어 implode
; 파일 크기가 더 작습니다.
// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);
// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();
// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
$csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
$csv .= '"' . $row['id'] . '",';
$csv .= '"' . $row['name'] . '",';
$csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
$csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
$csv .= PHP_EOL;
}
return $csv;
이것은 수만 행에서 수천 행까지 여러 보고서를 최적화 한 결론입니다. 세 가지 예는 1000 행 미만에서는 잘 작동했지만 데이터가 더 크면 실패합니다.
I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.
Works with over 100 lines, if you specify the size of the file in the headers simple call the get() method in your own class
function setHeader($filename, $filesize)
{
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 01 Jan 2001 00:00:01 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Type: text/x-csv');
// disposition / encoding on response body
if (isset($filename) && strlen($filename) > 0)
header("Content-Disposition: attachment;filename={$filename}");
if (isset($filesize))
header("Content-Length: ".$filesize);
header("Content-Transfer-Encoding: binary");
header("Connection: close");
}
function getSql()
{
// return you own sql
$sql = "SELECT id, date, params, value FROM sometable ORDER BY date;";
return $sql;
}
function getExportData()
{
$values = array();
$sql = $this->getSql();
if (strlen($sql) > 0)
{
$result = dbquery($sql); // opens the database and executes the sql ... make your own ;-)
$fromDb = mysql_fetch_assoc($result);
if ($fromDb !== false)
{
while ($fromDb)
{
$values[] = $fromDb;
$fromDb = mysql_fetch_assoc($result);
}
}
}
return $values;
}
function get()
{
$values = $this->getExportData(); // values as array
$csv = tmpfile();
$bFirstRowHeader = true;
foreach ($values as $row)
{
if ($bFirstRowHeader)
{
fputcsv($csv, array_keys($row));
$bFirstRowHeader = false;
}
fputcsv($csv, array_values($row));
}
rewind($csv);
$filename = "export_".date("Y-m-d").".csv";
$fstat = fstat($csv);
$this->setHeader($filename, $fstat['size']);
fpassthru($csv);
fclose($csv);
}
Just like @Dampes8N said:
$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
fputcsv($fp, $row);
}
fclose($fp);
Hope this helps.
pre-made code attached here. you can use it by just copying and pasting in your code:
https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv
참고URL : https://stackoverflow.com/questions/4249432/export-to-csv-via-php
'Programming' 카테고리의 다른 글
Visual Studio에서 생성자를 만드는 코드 조각 또는 바로 가기 (0) | 2020.06.12 |
---|---|
Java에서 참조로 문자열 전달? (0) | 2020.06.12 |
Android에서 GPS를 프로그래밍 방식으로 활성화 또는 비활성화하려면 어떻게해야합니까? (0) | 2020.06.12 |
Assert () 메소드의 기능은 무엇입니까? (0) | 2020.06.12 |
Git을 사용하여 원격 저장소에 초기 푸시를 어떻게 수행합니까? (0) | 2020.06.12 |