Search code examples
phpcsvflysystemthephpleague

How to fix "Uncaught Error: Call to a member function insertOne() on null" in php


I followed the solution introduced here https://stackoverflow.com/a/36041188/11295637 to create a new csv file and fetch specific columns of a large csv file to the new one. But, I get this error: Uncaught Error: Call to a member function insertOne() on null.

The code is as follows:

php

$new= Writer::createFromPath('path\to\file', 'w+');
$filename= Reader::createFromPath($filename, 'r');
          $filename->setOffset(1);
          $filename->each(function ($row) use ($indexes) {
            $new->insertOne($row);
            return true;
          });

The problem is that the new variable is undefined. I tried also

php
$new= Writer::createFromFileObject(new SplTempFileObject());

But I got the same error.


Solution

  • In PHP, if you want to reference a variable defined outside of a function, you must either (a) use a use qualifier in your anonymous function signature or (b) use a global statement inside your function.

    In your case, you have a use qualifier but it references a variable $indexes. I don't see an $indexes variable in your code, so you either need to add $new to that list or replace $indexes with $new.

    $new = Writer::createFromPath('path\to\file', 'w+');
    $filename = Reader::createFromPath($filename, 'r');
    $filename->setOffset(1);
    $filename->each(function ($row) use ($new) {
        $new->insertOne($row);
        return true;
    });
    

    To select only the indexes specified in the $indexes variable, you should select certain keys from $row and then rebuild a new row. You can use array_flip and array_intersect_key to do that.

    // convert [cat, dog] => [cat => 0, dog => 1]
    $indexKeys = array_flip($indexes);
    $filename->each(function ($row) use ($new, $indexKeys) {
        $selectedCols = array_intersect_key($row, $indexKeys);
        $new->insertOne($selectedCols);
        return true;
    });