2010-11-22 22 views
114

Diyelim ki bir veri tabanım var .... veri tabanından sahip olduğum şeyi bir CSV dosyasına (ve mümkünse metin dosyasına) PHP üzerinden verebileceğim bir yol var mı?PHP üzerinden CSV'ye aktar

+0

http://code.stephenmorley.org/php/create-downloadable-csv-files/ –

cevap

239

Herhangi bir diziden CSV içeriği oluşturmak için bu işlevi kişisel olarak kullanıyorum.

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

Kullanım Örneğin:

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

Sonra kullanıcı gibi bir şey kullanarak o dosyayı indirmek yapabilirsiniz

download_send_headers("data_export_" . date("Y-m-d") . ".csv"); 
echo array2csv($array); 
die(); 
+1

Yerel sunucu üzerinde çalışıyor, ama uzak bir içeriğiyle yeni bir sayfa ve hiçbir yükleme penceresi (benim ingilizce için üzgünüm) görüntüler –

+1

Hatalar için birkaç nedeni olabilir, onları bulmak için en kolay yolu apache hata bakmaktır .log dosyası. –

+0

Bu örneği kullanmaya çalışıyorum ve CSV'de elde ettiğim şey dizi2csv() işlevinin sonuçları yerine tam sayfa kaynağı HTML'm olsun? –

25

Tarihi bu komutu kullanarak dışa aktarabilirsiniz.

<?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); 
?> 

Önce ben iç içe yenisatırlar ve tırnak bir dizi etrafında herhangi bir sorun olsun parsecsv-for-php tavsiye bir dizide

+9

Ya da, fputcsv() öğesini standart bir getirme assoc döngüsünde yapabilir ve döndürülen sonuçlardan düz bir şekilde püskültebilirsiniz. – DampeS8N

+8

@ DampeS8N, +1 bir cümle içinde "plop down down out" kullanımı içindir. – AnchovyLegend

9

için mysql sunucudan veri yüklemek gerekir.

4

Dampes8N dediği @ gibi:

$result = mysql_query($sql,$conecction); 
$fp = fopen('file.csv', 'w'); 
while($row = mysql_fetch_assoc($result)){ 
    fputcsv($fp, $row); 
} 
fclose($fp); 

Bu yardımcı olur umarım.

+1

"fp = fopen ('file.csv', 'w'); " $ fp ile başlamalıdır, ancak 1 karaktere izin verilmez. – jay

12

, birleştirme waaaaaay hızlı (anladım) fputcsv hatta implode daha; Ve dosya boyutu küçüktür:

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

Bu on kadar binlerce satır, birkaç raporların optimizasyonu sonuç. Üç örnek 1000 satırın altında iyi çalıştı, ancak veriler büyüdüğünde başarısız oluyor.

3

İşleri 100'ün üzerinde çizgilerle, kendi sınıfında başlıklarında basit çağrı get() metodu dosyasının boyutunu belirtirseniz

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