Skip to content

Commit dc1fa81

Browse files
committed
Prepare for version 1.0.0
1 parent 3821e00 commit dc1fa81

File tree

5 files changed

+523
-2
lines changed

5 files changed

+523
-2
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/vendor
2+
composer.phar
3+
composer.lock

README.md

Lines changed: 240 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,240 @@
1-
# csv-php
2-
[Developing] PHP CSV writer & reader with settings of quoting enclosure and encoding
1+
<p align="center">
2+
<a href="https://codeigniter.com/" target="_blank">
3+
<img src="https://www.php.net/images/logos/php-logo-bigger.png" height="60px">
4+
</a>
5+
<h1 align="center">PHP CSV</h1>
6+
<br>
7+
</p>
8+
9+
PHP CSV writer &amp; reader with settings of quoting enclosure and encoding
10+
11+
[![Latest Stable Version](https://poser.pugx.org/yidas/csv/v/stable?format=flat-square)](https://packagist.org/packages/yidas/csv)
12+
[![License](https://poser.pugx.org/yidas/csv/license?format=flat-square)](https://packagist.org/packages/yidas/csv)
13+
14+
15+
Features
16+
--------
17+
18+
- *Support generating **Double Quotes** enclosure for all entities setting*
19+
20+
- *Support **Encoding** setting for local dialect*
21+
22+
- ***Elegent Interface** for setup and use*
23+
24+
---
25+
26+
OUTLINE
27+
-------
28+
29+
- [Demonstration](#demonstration)
30+
- [Requirements](#requirements)
31+
- [Installation](#installation)
32+
- [Usage](#usage)
33+
- [Options](#options)
34+
- [Writer](#writer)
35+
- [Reader](#reader)
36+
- [Exceptions](#exceptions)
37+
- [References](#references)
38+
39+
---
40+
41+
DEMONSTRATION
42+
-------------
43+
44+
Quickstart with specifying the file name directly:
45+
46+
```php
47+
// Read the CSV file
48+
$csvReader = new yidas\csv\Reader('/tmp/file.csv');
49+
$rows = $csvReader->readRows();
50+
$csvReader->fclose();
51+
// Write the CSV file
52+
$csvWriter = new yidas\csv\Writer('/tmp/file.csv');
53+
$csvWriter->writeRows($rows);
54+
$csvWriter->fclose();
55+
```
56+
57+
### Write to CSV
58+
59+
Open a file and use libray to write in CSV format:
60+
61+
```php
62+
$fp = fopen("/tmp/file.csv", 'w');
63+
64+
$csvWriter = new yidas\csv\Writer($fp, [
65+
// 'quoteAll' => true,
66+
// 'encoding' => 'UTF-8'
67+
]);
68+
$csvWriter->writeRow(["First", 'Second']);
69+
$csvWriter->writeRows([
70+
["Normal", 'Double"Quote'],
71+
["It's a context,\nNew line.", 'Encoded中文'],
72+
]);
73+
74+
fclose($fp);
75+
```
76+
77+
The content of generated CSV file will be:
78+
79+
```csv
80+
"First","Second"
81+
"Normal","Double""Quote"
82+
"It's a context,
83+
New line.","Encoded中文"
84+
```
85+
86+
> In default setting, it will always add double quotes with `UTF-8` encoding.
87+
88+
### Read from CSV
89+
90+
Open a CSV file with local encoding (`Big5`) and use libray to read with `UTF-8` encoding:
91+
92+
```php
93+
$fp = fopen("/tmp/file.csv", 'r');
94+
95+
$csvReader = new yidas\csv\Reader($fp, [
96+
'encoding' => 'Big5'
97+
]);
98+
$firstRow = $csvReader->readRow();
99+
$remainingRows = $csvReader->readRows();
100+
101+
fclose($fp);
102+
```
103+
104+
---
105+
106+
REQUIREMENTS
107+
------------
108+
109+
This library requires the following:
110+
111+
- PHP CLI 5.4.0+
112+
113+
---
114+
115+
INSTALLATION
116+
------------
117+
118+
Run Composer in your project:
119+
120+
composer require yidas/csv
121+
122+
Then you could use the class after Composer is loaded on your PHP project:
123+
124+
```php
125+
require __DIR__ . '/vendor/autoload.php';
126+
127+
use yidas\csv\Writer;
128+
use yidas\csv\Reader;
129+
```
130+
131+
---
132+
133+
USAGE
134+
-----
135+
136+
### Options
137+
138+
The options in parameter 2 for Writer/Reader class are as below:
139+
140+
#### quoteAll
141+
142+
Controls when quotes should be always generated by the writer.
143+
144+
#### Encoding
145+
146+
Controls which the encoding should be generated by the writer/reader.
147+
148+
> By defaule, Microsoft Excel will open CSV file with local encoding.
149+
> For example: Excel in Chinese(Traditional) Windows will open CSV with Big5 encoding.
150+
151+
### Writer
152+
153+
```php
154+
$csvWriter = new yidas\csv\Writer($fp, [
155+
// 'quoteAll' => true,
156+
// 'encoding' => 'UTF-8'
157+
]);
158+
```
159+
160+
#### writeRow()
161+
162+
Write the row parameter to the writer’s file stream, formatted according to the current setting.
163+
164+
```php
165+
public static array writeRow(array $rowData)
166+
```
167+
168+
#### writeRows()
169+
170+
Write the rows parameter to the writer’s file stream, formatted according to the current setting.
171+
172+
```php
173+
public static array writeRows(array $rowsData)
174+
```
175+
176+
### Reader
177+
178+
```php
179+
$csvReader = new yidas\csv\Reader($fp, [
180+
// 'encoding' => 'UTF-8'
181+
]);
182+
```
183+
184+
#### readRow()
185+
186+
Read a row from current file pointer.
187+
188+
```php
189+
public static array readRow()
190+
```
191+
192+
*Example:*
193+
194+
```php
195+
while ( ($row = $csvReader->readRow($file) ) !== FALSE ) {
196+
var_dump($row);
197+
}
198+
```
199+
200+
#### readRows()
201+
202+
Read all the rows from current file pointer.
203+
204+
```php
205+
public static array readRows()
206+
```
207+
208+
*Example:*
209+
210+
```php
211+
$rows = $csvReader->readRows();
212+
var_dump($rows);
213+
```
214+
215+
### Exceptions
216+
217+
```php
218+
219+
try {
220+
221+
$csvWriter = new yidas\csv\Writer($fp, [
222+
// 'quoteAll' => true,
223+
// 'encoding' => 'UTF-8'
224+
]);
225+
$csvWriter->writeRow(["First", 'Second']);
226+
227+
} catch (\Exception $e) {
228+
229+
echo 'Code:' . $e->getCode() . ' Message:' . $e->getMessage();
230+
}
231+
```
232+
233+
---
234+
235+
REFERENCES
236+
----------
237+
238+
- [Comma-separated values - Basic rules - Wiki](https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules)
239+
240+
- [RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files](https://datatracker.ietf.org/doc/html/rfc4180)

composer.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "yidas/csv",
3+
"description": "PHP CSV writer & reader with settings of quoting enclosure and encoding",
4+
"keywords": ["PHP", "CSV", "CSV Reader", "CSV Writer", "Excel CSV", "Quoting CSV"],
5+
"homepage": "https://github.com/yidas/csv-php",
6+
"type": "library",
7+
"license": "MIT",
8+
"support": {
9+
"issues": "https://github.com/yidas/csv-php/issues",
10+
"source": "https://github.com/yidas/csv-php"
11+
},
12+
"autoload": {
13+
"classmap": ["src"]
14+
}
15+
}

src/Reader.php

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
<?php
2+
3+
namespace yidas\csv;
4+
5+
use Exception;
6+
7+
/**
8+
* CSV Reader
9+
*
10+
* @author Nick Tsai <myintaer@gmail.com>
11+
* @version 1.0.0
12+
*/
13+
class Reader
14+
{
15+
// PHP csv handler uses UTF-8 encoding in default
16+
const DEFAULT_ENCODING = 'UTF-8';
17+
18+
/**
19+
* Current PHP file pointer stream of the reader
20+
*
21+
* @var resource
22+
*/
23+
protected $fileStream = null;
24+
25+
/**
26+
* Controls which the encoding should be generated by the writer
27+
*
28+
* @var boolean
29+
*/
30+
protected $encoding = null;
31+
32+
/**
33+
* Constructor
34+
*
35+
* @param resource|string File pointer or filePath
36+
* @param array $optParams API Key or option parameters
37+
* @return self
38+
*/
39+
function __construct($fileStream, $optParams=[])
40+
{
41+
// FilePath type input
42+
if (is_string($fileStream)) {
43+
// Check
44+
if (!file_exists($fileStream)) {
45+
throw new Exception("File not found at argument 1: {$fileStream}", 400);
46+
}
47+
48+
$fileStream = fopen($fileStream, 'r');
49+
}
50+
// Check file stream
51+
if (!is_resource($fileStream)) {
52+
throw new Exception("Invalid file stream at argument 1", 400);
53+
}
54+
55+
// Assignment
56+
$this->fileStream = $fileStream;
57+
$this->encoding = isset($optParams['encoding']) ? $optParams['encoding'] : $this->encoding;
58+
59+
return $this;
60+
}
61+
62+
/**
63+
* Read a row from current file pointer.
64+
*
65+
* @return array Returns an indexed array containing the fields read.
66+
*/
67+
public function readRow()
68+
{
69+
$row = fgetcsv($this->fileStream);
70+
71+
// Encoding handler
72+
if (is_array($row) && $this->encoding && $this->encoding!=self::DEFAULT_ENCODING) {
73+
foreach ($row as $key => & $value) {
74+
$value = mb_convert_encoding($value, self::DEFAULT_ENCODING, $this->encoding);
75+
}
76+
}
77+
78+
return $row;
79+
}
80+
81+
/**
82+
* Read all the rows from current file pointer.
83+
*
84+
* @param array $rowsData
85+
* @return self
86+
*/
87+
public function readRows()
88+
{
89+
$rows = [];
90+
while ( ($row = $this->readRow($this->fileStream) ) !== FALSE ) {
91+
$rows[] = $row;
92+
}
93+
94+
return $rows;
95+
}
96+
97+
/**
98+
* fclose for current file stream
99+
*
100+
* @return boolean Result
101+
*/
102+
public function fclose()
103+
{
104+
return fclose($this->fileStream);
105+
}
106+
}

0 commit comments

Comments
 (0)