Skip to content

Commit

Permalink
prepare 8.2.0 release
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jan 25, 2017
1 parent 37c2257 commit 74f75e0
Show file tree
Hide file tree
Showing 52 changed files with 4,554 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
/.php_cs export-ignore
/.scrutinizer.yml export-ignore
/.travis.yml export-ignore
/docs export-ignore
/README.md export-ignore
/scrutinizer.yml export-ignore
/CHANGELOG.md export-ignore
/CONDUCT.md export-ignore
/phpunit.xml export-ignore
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
vendor
build
docs
composer.lock
67 changes: 67 additions & 0 deletions docs/7.0/basic-usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
layout: default
title: Basic Usage
---

# Basic usage

<p class="message-info"><strong>Tips:</strong> Even though you can use the following methods with the <code>League\Csv\Writer</code> object. It is recommended to do so with the <code>League\Csv\Reader</code> class to avoid losing the file cursor position and getting unexpected results when inserting new data.</p>

Once your CSV object is [instantiated](/7.0/instantiation) and [configured](/7.0/properties/), you can start interacting with the data using a number of methods available to you. For starters, you can iterate over your newly object to extract each CSV row using the `foreach` construct.

~~~php
<?php

$reader = Reader::createFromPath('/path/to/my/file.csv');
foreach ($reader as $index => $row) {
//do something meaningful here with $row !!
//$row is an array where each item represent a CSV data cell
//$index is the CSV row index
}
~~~

<p class="message-notice">You can do more complex iterations <a href="/7.0/reading/">using the query methods</a> available on the <code>League\Csv\Reader</code> class only.</a></p>

## Outputting the CSV

### __toString()

Use the `echo` construct on the instantiated object or use the `__toString` method to show the CSV full content.

~~~php
<?php

echo $reader;
// or
echo $reader->__toString();
~~~

### output($filename = null)

If you only wish to make your CSV downloadable by forcing a file download just use the `output` method to force the use of the output buffer on the CSV content.

<p class="message-notice"> Since <code>version 7.0</code>, the method returns the number of characters read from the handle and passed through to the output.</p>

~~~php
<?php

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="name-for-your-file.csv"');
$reader->output();
~~~

The output method can take an optional argument `$filename`. When present you
can even remove more headers.

~~~php
<?php

$reader->output("name-for-your-file.csv");
~~~

The output methods **can only be affected by:**

- the [library stream filtering mechanism](/7.0/filtering/)
- the [BOM property](/7.0/bom/)

No other method or property have effect on them.
139 changes: 139 additions & 0 deletions docs/7.0/bom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
---
layout: default
title: CSV and BOM character
---

# Managing the BOM character

## Detecting the CSV BOM character

To improve interoperability with programs interacting with CSV, you can now manage the presence of a <abbr title="Byte Order Mark">BOM</abbr> character in your CSV content. <a href="http://en.wikipedia.org/wiki/Endianness" target="_blank">The character signals the endianness</a> of the CSV and its value depends on the CSV encoding character. To help you work with `BOM`, we are adding the following constants to the `Reader` and the `Writer` class:

* `BOM_UTF8` : `UTF-8` `BOM`;
* `BOM_UTF16_BE` : `UTF-16` `BOM` with Big-Endian;
* `BOM_UTF16_LE` : `UTF-16` `BOM` with Little-Endian;
* `BOM_UTF32_BE` : `UTF-32` `BOM` with Big-Endian;
* `BOM_UTF32_LE` : `UTF-32` `BOM` with Little-Endian;

They each represent the `BOM` character for each encoding character.

### getInputBOM()

This method will detect and return the `BOM` character used in your CSV if any.

~~~php
<?php

$reader = new Reader::createFromPath('path/to/your/file.csv');
$res = $reader->getInputBOM(); //$res equals null if no BOM is found

$reader = new Reader::createFromPat('path/to/your/msexcel.csv');
if (Reader::BOM_UTF16_LE == $reader->getInputBOM()) {
//the CSV file is encoded using UTF-16 LE
}
~~~

If you wish to remove the BOM character while processing your data, you can rely on the [query filters](/7.0/query-filtering/#stripbomstatus) to do so.

## Adding the BOM character to your CSV

### setOutputBOM($bom = null);

This method will manage the addition of a BOM character in front of your outputted CSV when you are:

- downloading a file using the `output` method
- ouputting the CSV directly using the `__toString()` method

`$bom` is a string representing the BOM character. To remove the `BOM` character just set `$bom` to an empty value like `null` or an empty string.

<p class="message-info">To ease writing the sequence you should use the <code>BOM_*</code> constants.</p>

### getOutputBOM()

This method will tell you at any given time what `BOM` character will be prepended to the CSV content.

<p class="message-info">For Backward compatibility by default <code>getOutputBOM</code> returns <code>null</code>.</p>

~~~php
<?php

$reader = new Reader::createFromPath('path/to/your/file.csv');
$reader->getOutputBOM(); //$res equals null;
$reader->setOutputBOM(Reader::BOM_UTF16LE);
$res = $reader->getOutputBOM(); //$res equals "\xFF\xFE";
echo $reader; //the BOM sequence is prepended to the CSV

~~~

## Software dependency

Depending on your operating system and on the software you are using to read/import your CSV you may need to adjust the encoding character and add its corresponding BOM character to your CSV.

<p class="message-warning">Out of the box, <code>League\Csv</code> assumes that your are using a <code>UTF-8</code> encoded CSV without any <code>BOM</code> character.</p>

In the examples below we will be using an existing CSV as a starting point. The code may vary if you are creating the CSV from scratch.

### MS Excel on Windows

On Windows, MS Excel, expects an UTF-8 encoded CSV with its corresponding `BOM` character. To fullfill this requirement, you simply need to add the `UTF-8` `BOM` character if needed as explained below:

~~~php
<?php

use League\Csv\Reader;

require '../vendor/autoload.php';

$reader = Reader::createFromPath('/path/to/my/file.csv');
$reader->setOutputBOM(Reader::BOM_UTF8);
//BOM detected and adjusted for the output
echo $reader->__toString();

~~~

### MS Excel on MacOS

On a MacOS system, MS Excel requires a CSV encoded in `UTF-16 LE` using the `tab` character as delimiter. Here's an example on how to meet those requirements using the `League\Csv` package.

~~~php
<?php

use League\Csv\Reader;
use League\Csv\Writer;
use lib\FilterTranscode;

require '../vendor/autoload.php';

//the current CSV is UTF-8 encoded with a ";" delimiter
$origin = Reader::createFromPath(__DIR__.'/data/prenoms.csv');

//let's convert the CSV to use a tab delimiter.

//we must use a real temp file to be able to rewind the cursor file
//without loosing the modifications
$writer = Writer::createFromPath('/tmp/toto.csv', 'w');

//we set the tab as the delimiter character
$writer->setDelimiter("\t");

//we insert csv data
$writer->insertAll($origin);

//let's switch to the Reader object
//Writer::output will failed because of the open mode
$csv = $writer->newReader();

//we register a Stream Filter class to convert the CSV into the UTF-16 LE
stream_filter_register(FilterTranscode::FILTER_NAME."*", "\lib\FilterTranscode");
$csv->appendStreamFilter(FilterTranscode::FILTER_NAME."UTF-8:UTF-16LE");

//we detect and adjust the output BOM to be used
$csv->setOutputBOM(Reader::BOM_UTF16_LE);
//all is good let's output the results
$csv->output('mycsvfile.csv');

~~~

Of note, we used the [filtering capability](/7.0/filtering) of the library to convert the CSV encoding character from `UTF-8` to `UTF-16 LE`.

You can found the code and the associated filter class in the [examples directory](https://github.com/thephpleague/csv/tree/master/examples).
67 changes: 67 additions & 0 deletions docs/7.0/converting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
layout: default
title: Converting your CSV
---

# Converting the CSV

the `League\Csv` object can convert your CSV document into JSON, XML and HTML format. In order to do so, the conversion methods assume that your CSV is UTF-8 encoded. To properly transcode your document into an UTF-8 compatible charset the recommended way is to use the <a href="/7.0/filtering/">library stream filtering mechanism</a>.

When this is not possible/applicable you can fallback to using the `setEncodingFrom` and `getEncodingFrom` methods.

If your CSV is not UTF-8 encoded some unexpected results and some errors could be thrown when trying to convert your data.

<p class="message-notice">Starting with <code>version 7.0</code>, when used with the <code>League\Csv\Reader</code> class, the conversion methods behavior are affected by the query options methods. Please refer to the <a href="/7.0/query-filtering">Query Filters page</a> for more informations and examples.</p>

<p class="message-notice">Starting with <code>version 7.1</code>, query filters are also available for conversion methods when using the <code>League\Csv\Writer</code> class</p>

## Convert to JSON format

Use the `json_encode` function directly on the instantiated object.

~~~php
<?php

echo json_encode($reader);
~~~

## Convert to XML

Use the `toXML` method to convert the CSV data into a `DomDocument` object. This
method accepts 3 optionals arguments to help you customize the XML tree:

- `$root_name`, the XML root name which defaults to `csv`;
- `$row_name`, the XML node element representing a CSV row which defaults to `row`;
- `$cell_name`, the XML node element for each CSV cell which defaults value is `cell`;

~~~php
<?php

$dom = $reader->toXML('data', 'line', 'item');
~~~

## Convert to HTML table

Use the `toHTML` method to convert the CSV data into an HTML table. This method
accepts an optional argument `$classname` to help you customize the table
rendering, by defaut the classname given to the table is `table-csv-data`.

~~~php
<?php

echo $reader->toHTML('table table-bordered table-hover');
~~~

## Example using data transcode before conversion

~~~php
<?php

$reader = Reader::createFromFileObject(new SplFileObject('/path/to/bengali.csv'));
//we are using the setEncodingFrom method to transcode the CSV into UTF-8
$reader->setEncodingFrom('iso-8859-15');
echo json_encode($reader);
//the CSV is transcoded from iso-8859-15 to UTF-8
//before being converted to JSON format;
echo $reader; //outputting the data is not affected by the conversion
~~~
102 changes: 102 additions & 0 deletions docs/7.0/examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
layout: default
title: Examples
---

# Examples

## Parsing a document

A simple example to show you how to parse a CSV document.

~~~php

<?php
use League\Csv\Reader;

$csv = Reader::createFromPath('/path/to/your/csv/file.csv');

//get the first row, usually the CSV header
$headers = $csv->fetchOne();

//get 25 rows starting from the 11th row
$res = $csv->setOffset(10)->setLimit(25)->fetchAll();
~~~

## Exporting a database table as a CSV document

A simple example to show you how to create and download a CSV from a `PDOStatement` object

~~~php

<?php
use League\Csv\Writer;

//we fetch the info from a DB using a PDO object
$sth = $dbh->prepare(
"SELECT firstname, lastname, email FROM users LIMIT 200"
);
//because we don't want to duplicate the data for each row
// PDO::FETCH_NUM could also have been used
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();

//we create the CSV into memory
$csv = Writer::createFromFileObject(new SplTempFileObject());

//we insert the CSV header
$csv->insertOne(['firstname', 'lastname', 'email']);

// The PDOStatement Object implements the Traversable Interface
// that's why Writer::insertAll can directly insert
// the data into the CSV
$csv->insertAll($sth);

// Because you are providing the filename you don't have to
// set the HTTP headers Writer::output can
// directly set them for you
// The file is downloadable
$csv->output('users.csv');
die;
~~~

## Importing a CSV into a database table

A simple example to show you how to import some CSV data into a database using a `PDOStatement` object

~~~php
<?php

use League\Csv\Reader;

//We are going to insert some data into the users table
$sth = $dbh->prepare(
"INSERT INTO users (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"
);

$csv = Reader::createFromPath('/path/to/your/csv/file.csv');
$csv->setOffset(1); //because we don't want to insert the header
$nbInsert = $csv->each(function ($row) use (&$sth) {
//Do not forget to validate your data before inserting it in your database
$sth->bindValue(':firstname', $row[0], PDO::PARAM_STR);
$sth->bindValue(':lastname', $row[1], PDO::PARAM_STR);
$sth->bindValue(':email', $row[2], PDO::PARAM_STR);

return $sth->execute(); //if the function return false then the iteration will stop
});
~~~

## More Examples

* [Selecting specific rows in the CSV](https://github.com/thephpleague/csv/blob/master/examples/extract.php)
* [Querying a CSV](https://github.com/thephpleague/csv/blob/master/examples/filtering.php)
* [Creating a CSV](https://github.com/thephpleague/csv/blob/master/examples/writing.php)
* [Merging 2 CSV documents](https://github.com/thephpleague/csv/blob/master/examples/merge.php)
* [Switching between modes from Writer to Reader mode](https://github.com/thephpleague/csv/blob/master/examples/switchmode.php)
* [Downloading the CSV](https://github.com/thephpleague/csv/blob/master/examples/download.php)
* [Converting the CSV into a Json String](https://github.com/thephpleague/csv/blob/master/examples/json.php)
* [Converting the CSV into a XML file](https://github.com/thephpleague/csv/blob/master/examples/xml.php)
* [Converting the CSV into a HTML Table](https://github.com/thephpleague/csv/blob/master/examples/table.php)
* [Using stream Filter on the CSV](https://github.com/thephpleague/csv/blob/master/examples/stream.php)

> The CSV data use for the examples are taken from [Paris Opendata](http://opendata.paris.fr/opendata/jsp/site/Portal.jsp?document_id=60&portlet_id=121)
Loading

0 comments on commit 74f75e0

Please sign in to comment.