Utwórz plik CSV dla użytkownika w PHP

Mam dane w bazie MySQL. Wysyłam użytkownikowi adres URL, aby uzyskać jego dane jako plik CSV.

Mam e-mail z linkiem, zapytaniem MySQL itp. zakryte.

Jak mogę, po kliknięciu linku, mieć wyskakujące okienko, aby pobrać CVS z rekordem z MySQL?

Mam już wszystkie informacje, aby zdobyć płytę. Po prostu nie widzę jak PHP stworzyć plik CSV i pozwolić im ściągnąć plik zrozszerzenie csv.

Author: d-_-b, 2008-10-20

20 answers

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

Etc

Edit: oto fragment kodu, którego używam do opcjonalnego kodowania pól CSV:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}
 269
Author: Oleg Barshay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-04 12:58:13
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

Php: / / output
fputcsv

 448
Author: Andrii Nemchenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:56:28

Oto ulepszona wersja funkcji z php.net to @ Andrzej napisał.

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

Jest naprawdę łatwy w użyciu i świetnie współpracuje z zestawami wyników MySQL (i)/PDO.

download_csv_results($results, 'your_name_here.csv');

Pamiętaj, aby exit() po wywołaniu tego, jeśli skończyłeś ze stroną.

 18
Author: Xeoncross,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:56:41

Oprócz wszystkich już wymienionych, być może będziesz musiał dodać:

header("Content-Transfer-Encoding: UTF-8");

Jest to bardzo przydatne podczas obsługi plików z wieloma językami, takimi jak nazwy osób lub miasta.

 16
Author: Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-18 15:09:54

Wątek jest trochę stary, wiem, ale na przyszłość i dla noobów jak ja:

Wszyscy tutaj wyjaśniają, jak utworzyć CSV, ale brakuje podstawowej części pytania: jak połączyć. Aby link do pobrania pliku CSV, wystarczy link do .PHP-plik, który z kolei odpowiada jako .plik csv. Robią to nagłówki PHP. Umożliwia to fajne rzeczy, takie jak dodawanie zmiennych do querystring i dostosowywanie wyjścia:

<a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>

My_csv_creator.php może współpracować z zmienne podane w zapytaniu i na przykład używają różnych lub dostosowanych zapytań do bazy danych, zmieniają kolumny pliku CSV, personalizują nazwę pliku itd., np.:

User_John_Doe_10_Dec_11.csv
 9
Author: LBJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-10 09:07:05

Utwórz swój plik, a następnie zwróć do niego odniesienie z odpowiednim nagłówkiem, aby uruchomić Zapisz jako - edytuj następujące elementy w razie potrzeby. Umieść swoje dane CSV w $csvdata.

$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);

header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
 7
Author: typemismatch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:56:49

Oto pełny przykład pracy przy użyciu PDO i zawierający nagłówki kolumn:

$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));    
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv'); 
exit();


function download_csv_results($results, $name)
{            
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");    
    fputcsv($outstream, array_keys($results[0]));

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}
 5
Author: Justin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:57:00

Najpierw Utwórz dane jako ciąg znaków z przecinkiem jako ogranicznikiem (oddzielonym znakiem ","). Coś takiego

$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine

$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                     //side it is recommended that the file name be different.

file_put_contents($file,$CSV_string);

/* Or try this code if $CSV_string is an array
    fh =fopen($file, 'w');
    fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
    fclose($fh);
*/
 4
Author: Behzad Ravanbakhsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 16:50:21

Hej to działa bardzo dobrze....!!!! Dzięki Peter Mortensen i Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

 3
Author: Kaddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-14 13:41:50

Metoda prosta -

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

Więc każda linia tablicy $data przejdzie do nowej linii nowo utworzonego pliku CSV. Działa tylko dla PHP 5 i nowszych.

 2
Author: user244641,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:57:37

Możesz po prostu zapisać swoje dane do pliku CSV używając funkcji fputcsv. spójrzmy na poniższy przykład. Zapis tablicy list do pliku CSV

$list[] = array("Cars", "Planes", "Ships");
$list[] = array("Car's2", "Planes2", "Ships2");
//define headers for CSV 
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file_name.csv');
//write data into CSV
$fp = fopen('php://output', 'wb');
//convert data to UTF-8 
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($list as $line) {
    fputcsv($fp, $line);
}
fclose($fp);
 2
Author: Shahbaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:57:44

Najprostszym sposobem jest użycie dedykowanej klasy CSV w następujący sposób:

$csv = new csv();
$csv->load_data(array(
    array('name'=>'John', 'age'=>35),
    array('name'=>'Adrian', 'age'=>23), 
    array('name'=>'William', 'age'=>57) 
));
$csv->send_file('age.csv'); 
 1
Author: Sergiu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-25 18:51:48

Zamiast:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

Użycie:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}
 1
Author: Joshua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 16:53:53

Już nadeszło bardzo dobre rozwiązanie. Po prostu wklejam całkowity kod, aby początkujący uzyskali całkowitą pomoc

<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");

require_once("includes/functions.php"); //necessary mysql connection functions here

//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
    $csv_head[] =  $row['Field'];
}
echo implode(",", $csv_head)."\n";

//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    foreach ($row as $key => $value) {
            //there may be separator (here I have used comma) inside data. So need to put double quote around such data.
        if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
            $row[$key] = '"' . str_replace('"', '""', $value) . '"';
        }
    }
    echo implode(",", $row)."\n";
}

?>

Zapisałem ten kod w csv-download.php

Teraz zobacz jak wykorzystałem te dane do pobrania pliku csv

<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>

Więc po kliknięciu linku Pobierz plik bez brania mnie do csv-download.strona php w przeglądarce.

 1
Author: zahid9i,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-17 16:19:35

Aby wysłać go jako plik CSV i nadać mu nazwę pliku, użyj header():

Http://us2.php.net/header

header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');

Jeśli chodzi o tworzenie samego pliku CSV, wystarczy zapętlić zestaw wyników, sformatować wyjście i wysłać je, tak jak każda inna zawartość.

 0
Author: Gavin M. Roy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-20 03:15:08

Oto jeden zrobiłem wcześniej, pobieranie danych między pewnymi datami. Mam nadzieję, że to pomoże.

<?php
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    ini_set('display_errors',1);
    $private=1;
    error_reporting(E_ALL ^ E_NOTICE);

    mysql_connect("localhost", "user", "pass") or die(mysql_error());
    mysql_select_db("db") or die(mysql_error());

    $start = $_GET["start"];
    $end = $_GET["end"];

    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error());

    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        $result.="{$row['email']},";
        $result.="\n";
        echo $result;
    }
?>
 0
Author: Connor Burton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 16:53:20

Pisanie własnego kodu CSV jest prawdopodobnie stratą czasu, wystarczy użyć pakietu takiego jak league / csv-zajmuje się wszystkim trudnym dla Ciebie materiałem, dokumentacja jest dobra i bardzo stabilna/niezawodna:

Http://csv.thephpleague.com/

Musisz używać composera. Jeśli nie wiesz co to jest kompozytor to Gorąco polecam zajrzyj: https://getcomposer.org/

 0
Author: John Hunt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-06 08:15:29
<?
    // Connect to database
    $result = mysql_query("select id
    from tablename
    where shid=3");
    list($DBshid) = mysql_fetch_row($result);

    /***********************************
    Write date to CSV file
    ***********************************/

    $_file = 'show.csv';
    $_fp = @fopen( $_file, 'wb' );

    $result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");

    while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
    {
        $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
        @fwrite( $_fp, $_csv_data);
    }
    @fclose( $_fp );
?>
 0
Author: 3 revs, 3 users 69%Vish00722,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:58:02

Jak pisać w pliku CSV za pomocą skryptu PHP? Właściwie to też tego szukałem. Jest to swego rodzaju łatwe zadanie z PHP. fputs ( handler, content) - Ta funkcja działa wydajnie dla mnie. Najpierw musisz otworzyć plik, w którym chcesz zapisać zawartość za pomocą fopen($CSVFileName, 'WB').

$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);

//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
    $line = “”;
    $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
    $line .= “\n”;
    fputs($fp, $line);
}
 0
Author: ntzm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 13:58:14

Umieść w zmiennej $output Dane CSV i echo z poprawnymi nagłówkami

header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;
 -1
Author: Lorenzo Massacci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-07 01:10:23