PHP code example of goodby / csv

1. Go to this page and download the library: Download goodby/csv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

goodby / csv example snippets


use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

$lexer = new Lexer(new LexerConfig());
$interpreter = new Interpreter();
$interpreter->addObserver(function(array $row) {
    // do something here.
	// for example, insert $row to database.
});
$lexer->parse('data.csv', $interpreter);

use Goodby\CSV\Import\Standard\LexerConfig;

$config = new LexerConfig();
$config
    ->setDelimiter("\t") // Customize delimiter. Default value is comma(,)
    ->setEnclosure("'")  // Customize enclosure. Default value is double quotation(")
    ->setEscape("\\")    // Customize escape character. Default value is backslash(\)
    ->setToCharset('UTF-8') // Customize target encoding. Default value is null, no converting.
    ->setFromCharset('SJIS-win') // Customize CSV file encoding. Default value is null.
;

use Goodby\CSV\Export\Standard\ExporterConfig;

$config = new ExporterConfig();
$config
    ->setDelimiter("\t") // Customize delimiter. Default value is comma(,)
    ->setEnclosure("'")  // Customize enclosure. Default value is double quotation(")
    ->setEscape("\\")    // Customize escape character. Default value is backslash(\)
    ->setToCharset('SJIS-win') // Customize file encoding. Default value is null, no converting.
    ->setFromCharset('UTF-8') // Customize source encoding. Default value is null.
    ->setFileMode(CsvFileObject::FILE_MODE_WRITE) // Customize file mode and choose either write or append. Default value is write ('w'). See fopen() php docs
;

use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\LexerConfig;

$interpreter = new Interpreter();
$interpreter->unstrict(); // Ignore row column count consistency

$lexer = new Lexer(new LexerConfig());
$lexer->parse('rough.csv', $interpreter);

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

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

$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);

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

$temperature = array();

$config = new LexerConfig();
$config->setDelimiter("\t");
$lexer = new Lexer($config);

$interpreter = new Interpreter();
$interpreter->addObserver(function(array $row) use (&$temperature) {
    $temperature[] = array(
        'temperature' => $row[0],
        'city'        => $row[1],
    );
});

$lexer->parse('temperature.tsv', $interpreter);

print_r($temperature);

use Goodby\CSV\Export\Standard\Exporter;
use Goodby\CSV\Export\Standard\ExporterConfig;

$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]'),
));

use Goodby\CSV\Export\Standard\Exporter;
use Goodby\CSV\Export\Standard\ExporterConfig;
use Goodby\CSV\Export\Standard\CsvFileObject;
use Goodby\CSV\Export\Standard\Collection\PdoCollection;

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');

$pdo->query('CREATE TABLE IF NOT EXISTS user (id INT, `name` VARCHAR(255), email VARCHAR(255))');
$pdo->query("INSERT INTO user VALUES(1, 'alice', '[email protected]')");
$pdo->query("INSERT INTO user VALUES(2, 'bob', '[email protected]')");
$pdo->query("INSERT INTO user VALUES(3, 'carol', '[email protected]')");

$config = new ExporterConfig();
$exporter = new Exporter($config);

$stmt = $pdo->prepare("SELECT * FROM user");
$stmt->execute();

$exporter->export('php://output', new PdoCollection($stmt));

use Goodby\CSV\Export\Standard\Exporter;
use Goodby\CSV\Export\Standard\ExporterConfig;

use Goodby\CSV\Export\Standard\Collection\CallbackCollection;

$data = array();
$data[] = array('user', 'name1');
$data[] = array('user', 'name2');
$data[] = array('user', 'name3');

$collection = new CallbackCollection($data, function($row) {
    // apply custom format to the row
    $row[1] = $row[1] . '!';

    return $row;
});

$config = new ExporterConfig();
$exporter = new Exporter($config);

$exporter->export('php://stdout', $collection);

namespace AcmeBundle\ExampleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DefaultController extends Controller
{
	public function csvExportAction()
	{
		$conn = $this->get('database_connection');

		$stmt = $conn->prepare('SELECT * FROM somewhere');
		$stmt->execute();

		$response = new StreamedResponse();
		$response->setStatusCode(200);
		$response->headers->set('Content-Type', 'text/csv');
		$response->setCallback(function() use($stmt) {
			$config = new ExporterConfig();
			$exporter = new Exporter($config);

		    $exporter->export('php://output', new PdoCollection($stmt->getIterator()));
		});
		$response->send();

		return $response;
	}
}
bash
php composer.phar install