PHP code example of okneloper / csv

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

    

okneloper / csv example snippets



use \Okneloper\Csv\Stream\Input\FileStream;
use \Okneloper\Csv\CsvReader;

// read CSV data from a file
$dataSource = new FileStream($file);

// creata a reader
$csv = new CsvReader($dataSource);

// read rows one by one
while ($row = $csv->read()) {
    echo $row->position; // value for the row in column 0 with header 'position'
    echo $row->animal;   // value for the row in column 1 with header 'animal'
    echo $row->weight;   // value for the row in column 2 with header 'weight'
    echo $row["weight"]; // also supports array syntax 
}


    $dataSource = new \Okneloper\Csv\Stream\Input\FileStream($file);

    $dataSource = new \Okneloper\Csv\Stream\StringStream("position,animal,weight\n1,Blue whale,180 tonnes\n2,African Elephant,6350 kg\n3,Brown Bear,1 ton");

    $csv = new \Okneloper\Csv\CsvReader($dataSource);

    while ($row = $csv->read()) {
        print_r($row->toArray());
    }

echo $row['position'];

echo $row->position;

$csv = new \Okneloper\Csv\CsvReader($dataSource);

$csv = new \Okneloper\Csv\CsvReader($dataSource, true, ['Nr', 'Who', 'HowMuch']);

$csv = new \Okneloper\Csv\CsvReader($dataSource, false, ['Nr', 'Who', 'HowMuch']);

$csv = new \Okneloper\Csv\CsvReader($dataSource, false, null);

Array
(
    [0] => position
    [1] => animal
    [2] => weight
)
Array
(
    [0] => 1
    [1] => Blue whale
    [2] => 180 tonnes
)
...