user1721449 user1721449 - 1 day ago 4
PHP Question

fgetcsv throwing error when calling from CLI

Can run my php file fine when checking it via browser, but throws an infinite loop error when run via CLI:

fgetcsv() expects parameter 1 to be resource, boolean given on line 30 (while line)

Code:

readCSV("feeds/data.csv");
function readCSV($csvFile) {
$count = 0; //for counting array objects
$storedQuotes = array();
$handle = fopen($csvFile, 'r');
//fgetcsv($file, 1000, ","); //remove first line

while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {

$quote = $line[2];
$author = $line[1];

//add element to $csv_arr with $quote and $author
$csv_arr[]=array(
"quote" => $quote,
"author" => $author
);
}

fclose($file);
}


How can I get my program to run via php cli?

Answer

Check if $handle is a resource (or is false) first. For example:

$handle = fopen($csvFile, 'r');
if(false !=== $handle) {
  // do while{} here
}
else {
  echo "Could not open $csvFile for reading";
}

Also, in CLI, your file paths are different. So you need to be more explicit. The easiest way to do this, if $csvFile is located in a relative path to the script, is to define the path such as:

__DIR__ . "feeds/data.csv"

Comments