1

Here's what I'm doing:

<?php
$csvObj = new Csv2Parser($file);
$csvObj->loopContents();
$csvObj->looplimitrows = 9; // why does this get ignored?
?>

This looplimitrows is always returning 5 rows, instead of the 9 I am wanting. Am I not doing it right?

Here's the Class:

class Csv2Parser
{
    private $filepath; 

    public $looplimitrows = 5; 

    /*
      .... __construct() goes here...
    */

    public function loopContents(){
      $looplimitrows = $this->looplimitrows;
      $linecount=0;
      $fp = fopen($targetFile, "r"); // open the file
      while ($line = fgetcsv($fp)) {
      $linecount++;

        if(!empty($looplimitrows) && $linecount > $looplimitrows){ break; }

        echo $line[0]; // first column only

      }//eof while()

}

2 Answers 2

3

It get's ignored as it's not set before you loop through the csv therefor the limit is 5 as that's it's default value.

public $looplimitrows = 5;

You need to set Csv2Parser::looplimirows as below.

$csvObj = new Csv2Parser($file);
$csvObj->looplimitrows = 9; // It needs to go here.
$csvObj->loopContents();

Alternatively, try this :)

<?php
ini_set('auto_detect_line_endings', true);

class Csv2Parser {

    private $rowLimit = NULL;

    private $fileHandle = NULL;
    private $data = NULL;

    public function __construct($filename) 
    {

        if (!file_exists($filename))
            throw new Exception("Can't find file:" . $filename);

        $this->fileHandle = fopen($filename, "r");
    }


    public function get($n) 
    {
        $this->rowLimit = (int) $n;

        return $this;
    }


    public function rows()
    {
        $linecount = 0;

        while (($line = fgetcsv($this->fileHandle, 1000, ",")) !== false) {
            $linecount++;

            if(!is_null($this->rowLimit) && $linecount > $this->rowLimit)
                break;


            $this->data[] = $line;

        }

        return $this->data;
    }
}


$csv = new Csv2Parser("my.csv");
print_r($csv->get(9)->rows()); // Could not be more self explanitory
Sign up to request clarification or add additional context in comments.

Comments

0

You are calling the loopContents() method without first setting the public variable looplimitrows. So the method executes with the default value of looplimitrows. First set the looplimitrows public variable and call the loopContents() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.