0

I seem to be having a problem reading in the lines from US.txt in pset8. I think it must be something I am not understanding about fgetcsv. Here is my code:

<?php

$numArgs = count($argv);

if($numArgs != 2)
{
   // invalid number of command line arguments
}
else
{    
    $filepath = $argv[1];

    if(is_readable($filepath))
    {            
        print("is readable\n");
        $file = fopen($filepath, 'r');

        if($file)
        {
            print("file good\n");
        }

        while($row = fgetcsv($file, 512, "\t") !== FALSE)
        {                                                            
            print($row[0]);               
        }

        fclose($file);
    }
}

?>

The values I get are NULL for $row[0] and if I just print the value of $row I get 1. I would have expected an array with the elements of the line from the file separated by the "\t" delimiter. Is there something obvious that I'm doing wrong? Thanks in advance!

2
  • First off, try using $argc instead of count(). Also, what do you want to do if $argc !=2, return an error message? But more importantly, is $row populating properly? Try printing out the values using print_r or var_dump
    – ronga
    Oct 14 '15 at 1:43
  • Thanks, yeah didn't think about argc for some reason. Also, I do intend to have some error handling if argc is other than 2. But for now my concern is reading in the data from the file. It doesn't seem to me that $row is populating correctly. If the function works I should get an array with tokens separated by the delimiter correct? Instead $row seems to be assigned a number value of 1. Oct 14 '15 at 2:05
1
  1. You're missing () in your while loop, should be:

    while(($row = fgetcsv($file, 512, "\t")) !== FALSE)

  2. Also, your current code only prints out $row[0], you want to check all the values as I mentioned above, or at least the first couple of values.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .