Skip to content

Commit

Permalink
add example
Browse files Browse the repository at this point in the history
  • Loading branch information
suin committed Dec 6, 2012
1 parent 8da3492 commit d0ab721
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 3 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@

[![Build Status](https://secure.travis-ci.org/goodby/csv.png?branch=master)](https://travis-ci.org/goodby/csv)

## What is Csv?
## What is "Goodby CSV"?

editing...
Goodby CSV is a flexible and extendable open-source CSV import/export library.

```php
// Sample code... writing...
```

## Requirements

Expand Down
34 changes: 34 additions & 0 deletions exmaple/sample.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

require_once __DIR__.'/../vendor/autoload.php'; // load composer

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;
use Goodby\CSV\Export\Standard\Exporter;
use Goodby\CSV\Export\Standard\ExporterConfig;

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));
$pdo->query('CREATE TABLE IF NOT EXISTS user (id INT, `name` VARCHAR(255), email VARCHAR(255))');

// Importing
$config = new LexerConfig();
$lexer = new Lexer($config);
$interpreter = new Interpreter();
$interpreter->addObserver(function(array $columns) use ($pdo) {
$stmt = $pdo->prepare('INSERT INTO user (id, name, email) VALUES (?, ?, ?)');
$stmt->execute($columns);
});
$lexer->parse('user.csv', $interpreter);

// Exporting
$config = new ExporterConfig();
$exporter = new Exporter($config);
$exporter->export('php://output', array(
array('1', 'alice', '[email protected]'),
array('2', 'bob', '[email protected]'),
array('3', 'carol', '[email protected]'),
));

3 changes: 3 additions & 0 deletions exmaple/user.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1,alice,[email protected]
2,bob,[email protected]
3,carol,[email protected]
7 changes: 6 additions & 1 deletion src/Goodby/CSV/Export/Standard/Exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ private function replaceNewline($pointer, $newline)
* has hardcoded "\n", this method seek one character back
* and replace newline code with what client code wish.
*/
fseek($pointer, ftell($pointer) - 1);
$result = @fseek($pointer, ftell($pointer) - 1);

if ( $result === -1 ) {
return; // case: php://output, php://stdout and so on
}

fputs($pointer, $newline);
}

Expand Down

0 comments on commit d0ab721

Please sign in to comment.