Citation Envoyé par Ghostaunt Voir le message
Salut j'ai du mal à saisir ta remarque, je n'écris pas directement dans un fichier là ?
ah oui en effet tu écris les lignes avant, fputcsv te permet de le faire avec un array

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class CSV
{
    private $headers;
    private $file_name;
    private $delimiter;
    private $enclosure;
    private $handle;
 
    public function __construct($delimiter = ';', $enclosure = '"')
    {
        $this->handle = fopen('php://memory', 'rb+');
        $this->delimiter = $delimiter;
        $this->enclosure = $enclosure;
    }
 
    public function headers(array $headers)
    {
        $this->headers = $headers;
        return $this;
    }
 
    public function insert(array $fields)
    {
        fputcsv($this->handle, $fields, $this->delimiter, $this->enclosure);
        return $this;
    }
 
    public function output($file_name = 'temp.csv')
    {
        header("Content-type: text/csv");
        header("Content-Disposition: attachment;filename=$file_name");
 
        if (!empty($this->headers)) {
            $header = fopen('php://output', 'rb+');
            fputcsv($header, $this->headers, $this->delimiter, $this->enclosure);
        }
 
        rewind($this->handle);
        fpassthru($this->handle);
        exit;
    }
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$csv = new CSV();
 
$csv->headers(array('id', 'test', 'blabla'))
    ->insert(array(1, 'test1', 'machin1'))
    ->insert(array(2, 'test2', 'machin2'))
    ->insert(array(3, 'test3', 'machin3'))
    ->output();
 
/*
id;test;blabla
1;test1;machin1
2;test2;machin2
3;test3;machin3
*/