PHP code example of godsgood33 / csv-reader

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

    

godsgood33 / csv-reader example snippets


$header = array_flip(fgetcsv($fh));
/*
 array(
     'column1' => 0,
     'column2' => 1,
     'column3' => 2,
     ...
 )
 */

foreach($data = fgetcsv($fh)) {
  // $data is now a numeric indexed array
  // $header['column1'] will return 0 so $data[$header['column1']] will return the value of the first index in the array to the CSV
  $column1 = $data[$header['column1']];
}

$column1 = $data[$column1HeaderIndex];

$reader = new Reader($csvFilename);

// sets the column delimiter to the semi-colon, the header column is now the second row and changes the header properties to all the lower case
$reader = new Reader($csvFilename, [
    'delimiter' => ';',
    'enclosure' => "'",
    'header' => 1,
    'headerCase' => Header::TO_LOWER,
]);

do {
    $name = $reader->name;
    $phone = $reader->phone;
    $email = $reader->email;
} while($reader->next());

// this will first check that the 'name', 'phone', and 'email' columns are present before proceeding...throws a "InvalidHeaderOrField" exception is something is missing
$reader = new Reader('file.csv', ['

$reader = new Reader('file.csv', [
  'alias' => [
      'digits' => 'phone',
      'zip' => 'postalcode'
    ]
  ]
);

$phone = $reader->digits;
$phone = $reader->phone;