PHP code example of volcanus / csv-parser

1. Go to this page and download the library: Download volcanus/csv-parser 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/ */

    

volcanus / csv-parser example snippets




$parser = new \Volcanus\CsvParser\CsvParser([
    'delimiter'      => ',',
    'enclosure'      => '"',
    'escape'         => '"',
    'inputEncoding'  => 'SJIS',
    'outputEncoding' => 'UTF-8',
    'sanitizing'     => true,
]);

$csvFile = new \SplFileObject('php://temp', '+r');
$csvFile->fwrite(mb_convert_encoding("1,田中\r\n", 'SJIS', 'UTF-8'));
$csvFile->fwrite(mb_convert_encoding("2,山田\r\n", 'SJIS', 'UTF-8'));
$csvFile->fwrite(mb_convert_encoding("3,鈴木\r\n", 'SJIS', 'UTF-8'));
$csvFile->rewind();

$users = [];

foreach ($csvFile as $line) {

    // 1件分のレコード取得が終了するまで各行をパース
    if (!$parser->parse($line)) {
        continue;
    }

    $csv = $parser->getBuffer();

    $row = $parser->convert($csv);

    // 空行にはNULLが返されるので無視
    if (is_null($row)) {
        continue;
    }

    // CSVのフィールドをオブジェクトに取得
    $user = new \stdClass();
    $user->id   = $row[0];
    $user->name = $row[1];

    $users[] = $user;
}

echo $users[0]->id; // 1
echo $users[0]->name; // 田中
echo $users[1]->id; // 2
echo $users[1]->name; // 山田
echo $users[2]->id; // 3
echo $users[2]->name; // 鈴木