Get next row from a CSV file
This simplifies the reading of a CSV file by abstracting file-open, get-header, get-rows and file-close operations into a single method call, where all those operations are handled internally. All you have to
do is keep calling the $files->getCSV($filename)
method until it returns false. This method will also
skip over blank rows by default, unlike PHP’s fgetcsv() which will return a 1-column row with null value.
This method should always be used in a loop, meaning you must keep calling it until it returns false. Otherwise a CSV file may be unintentionally left open. If you can't do that then use getAllCSV() instead.
For the method $options
argument note that the length
, separator
, enclosure
and escape
options
all correspond to the identically named PHP fgetcsv
arguments.
Example foods.csv file (first row is header):
Example of reading the foods.csv file above:
Available since version 3.0.197.
Examples
Food,Type,Color
Apple,Fruit,Red
Banana,Fruit,Yellow
Spinach,Vegetable,Green
while($row = $files->getCSV('/path/to/foods.csv')) {
echo "Food: $row[Food] ";
echo "Type: $row[Type] ";
echo "Color: $row[Color] ";
}
Usage
// basic usage
$array = $files->getCSV(string $filename);
// usage with all arguments
$array = $files->getCSV(string $filename, array $options = []);
Arguments
Name | Type(s) | Description |
---|---|---|
filename | string | CSV filename to read from |
options (optional) | array |
|
Return value
array
false
Returns array for next row or boolean false when there are no more rows.
API reference based on ProcessWire core version 3.0.236