Skip to content

Commit 2181188

Browse files
committed
First commit
0 parents  commit 2181188

File tree

4 files changed

+265
-0
lines changed

4 files changed

+265
-0
lines changed

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2016 E-COMMIT
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
CSV Table Generator
2+
====================
3+
4+
Create a CSV file with PHP array.
5+
6+
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/28c792f3-d5ac-4efb-9500-c7bf7cc06b7c/big.png)](https://insight.sensiolabs.com/projects/28c792f3-d5ac-4efb-9500-c7bf7cc06b7c)
7+
8+
Installation
9+
-------------
10+
11+
To install csv-table-generator with Composer just run :
12+
13+
```bash
14+
$ composer require ecommit/csv-table-generator
15+
```
16+
17+
18+
19+
Usage
20+
------
21+
22+
```php
23+
use Ecommit\CsvTableGenerator\Csv;
24+
25+
$csv = new Csv('/home/test', 'myfilename', array(
26+
'header' => array(
27+
'Column A',
28+
'Column B',
29+
),
30+
));
31+
32+
$csv->write(array('Hello', 'world')); //Add line
33+
$csv->write(array('Test1', 'Test2')); //Add line
34+
$csv->close();
35+
```
36+
37+
/home/test/myfilename.csv is generated :
38+
39+
```
40+
"Column A","Column B"
41+
Hello,world
42+
Test1,Test2
43+
```
44+
45+
**Constructor arguments :**
46+
47+
* **String $pathDir** : Path folder (when CSV file is generated) **Required**
48+
* **String $filename** : Filename (without path folder and extension) **Required**
49+
* **Array $options** : Options. See below
50+
51+
**Availabled options :**
52+
53+
* **header** (array) : Header array. If empty, no header. **Default: array()**
54+
* **max_lines** (null | int) : Max lines per CSV file. If lines > max_lines, many files are generated. **Default: null**
55+
* **delimiter** (string) : CSV delimiter. **Default: ,**
56+
* **enclosure** (string) : CSV enclosure. **Default: "**
57+
* **eol** (string - Csv::EOL_ constants) : EOF(End Of Line) character. See **Csv::EOL_** constants. **Default: Csv::EOL_LF**. If **Csv::EOL_CRLF**
58+
is used, **unix2dos** program is required
59+
* **unix2dos_path** (string) : Unix2dos path. Only used if eol=Csv::EOL_CRLF. **Default: /usr/bin/unix2dos**
60+
* **add_utf8_bom** (bool) : Add or not UTF8 bom. **Default: false**
61+
62+
##License
63+
64+
This librairy is under the MIT license. See the complete license in *LICENSE* file.

composer.json

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "ecommit/csv-table-generator",
3+
"description": "Create a CSV file with PHP array.",
4+
"keywords": ["csv", "array", "table"],
5+
"type": "library",
6+
"license": "MIT",
7+
"authors": [
8+
{
9+
"name": "Hubert Lecorche",
10+
"email": "contact@e-commit.fr"
11+
}
12+
],
13+
"autoload": {
14+
"psr-4": { "Ecommit\\CsvTableGenerator\\": "src/" }
15+
},
16+
"extra": {
17+
"branch-alias": {
18+
"dev-master": "1.0.x-dev"
19+
}
20+
}
21+
}

src/Csv.php

+159
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
<?php
2+
3+
/**
4+
* This file is part of the csv-table-generator package.
5+
*
6+
* (c) E-commit <contact@e-commit.fr>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Ecommit\CsvTableGenerator;
13+
14+
class Csv
15+
{
16+
const EOL_LF = 'LF';
17+
const EOL_CRLF = 'CR+LF';
18+
19+
protected $handle;
20+
protected $pathDir;
21+
protected $filename;
22+
protected $currentFile;
23+
protected $header;
24+
protected $maxLines;
25+
protected $delimiter;
26+
protected $enclosure;
27+
protected $fileNumber = 0;
28+
protected $lines;
29+
protected $unixToDos = false;
30+
protected $unixToDosPath;
31+
protected $addUtf8Bom = false;
32+
33+
/**
34+
* Constructor
35+
*
36+
* @param string $pathDir Path folder
37+
* @param string $filename Filename (without path folder and extension)
38+
* @param array $options See README.md
39+
*/
40+
public function __construct($pathDir, $filename, $options = array()) {
41+
$defaultOptions = array(
42+
'header' => array(),
43+
'max_lines' => null,
44+
'delimiter' => ',',
45+
'enclosure' => '"',
46+
'eol' => self::EOL_LF,
47+
'unix2dos_path' => '/usr/bin/unix2dos',
48+
'add_utf8_bom' => false,
49+
);
50+
$options = array_merge($defaultOptions, $options);
51+
52+
//Test folder
53+
$realPath = \realpath($pathDir);
54+
if (false === $realPath || !\is_writable($realPath)) {
55+
throw new \Exception(sprintf('Folder %s does not exist or is not writable', $pathDir));
56+
}
57+
58+
$this->pathDir = $realPath;
59+
$this->filename = $filename;
60+
$this->header = $options['header'];
61+
if (empty($options['max_lines'])) {
62+
$this->maxLines = null;
63+
} else {
64+
$this->maxLines = \intval($options['max_lines']);
65+
}
66+
$this->delimiter = $options['delimiter'];
67+
$this->enclosure = $options['enclosure'];
68+
69+
if (self::EOL_CRLF === $options['eol']) {
70+
$this->unixToDos = true;
71+
}
72+
$this->unixToDosPath = $options['unix2dos_path'];
73+
74+
$this->addUtf8Bom = $options['add_utf8_bom'];
75+
76+
$this->open();
77+
}
78+
79+
/**
80+
* Open CSV file
81+
*/
82+
protected function open()
83+
{
84+
if ($this->handle) {
85+
throw new \Exception(sprintf('The file %s is already open', $this->filename));
86+
}
87+
$this->fileNumber++;
88+
$this->lines = 0;
89+
$filename = $this->filename;
90+
if ($this->fileNumber > 1) {
91+
$filename .= '-' . $this->fileNumber;
92+
}
93+
$this->currentFile = $this->pathDir . '/' . $filename . '.csv';
94+
$this->handle = \fopen($this->currentFile, 'wb'); //Binary is forced. EOL = "\n"
95+
if (false === $this->handle) {
96+
throw new \Exception(sprintf('Error during the opening of the %s file', $this->filename));
97+
}
98+
if ($this->addUtf8Bom) {
99+
if (!\fputs($this->handle, chr(0xEF).chr(0xBB).chr(0xBF))) {
100+
throw new \Exception(sprintf('Error during the UTF8-BOM writing in %s file', $this->filename));
101+
}
102+
}
103+
if (!empty($this->header)) {
104+
$this->write($this->header);
105+
$this->lines = 0;
106+
}
107+
}
108+
109+
/**
110+
* Close CSV file
111+
*/
112+
public function close()
113+
{
114+
if ($this->handle) {
115+
\fclose($this->handle);
116+
$this->handle = null;
117+
118+
if ($this->unixToDos) {
119+
passthru(sprintf('%s %s', $this->unixToDosPath, $this->currentFile), $returnVar);
120+
if (0 !== $returnVar) {
121+
throw new \Exception(sprintf('Unix2dos error (%s file)', $this->filename));
122+
}
123+
}
124+
$this->currentFile = null;
125+
}
126+
}
127+
128+
/**
129+
* Create new CSV file
130+
*/
131+
protected function newFile()
132+
{
133+
$this->close();
134+
$this->open();
135+
}
136+
137+
/**
138+
* Add line in CSV file
139+
* @param array $data
140+
*/
141+
public function write($data)
142+
{
143+
if (!$this->handle) {
144+
throw new \Exception(sprintf('Handle does not exist. File %s', $this->filename));
145+
}
146+
147+
//New file
148+
if ($this->maxLines && $this->maxLines == $this->lines) {
149+
$this->newFile();
150+
}
151+
152+
//Write
153+
if (false === \fputcsv($this->handle, $data, $this->delimiter, $this->enclosure)) {
154+
throw new \Exception(sprintf('Error during the writing in %s file', $this->filename));
155+
}
156+
157+
$this->lines++;
158+
}
159+
}

0 commit comments

Comments
 (0)