coseva
coseva copied to clipboard
Add toCSV method
A coworker of mine needed a CSV to be filtered this week and it involved something a little more complex than what Excel offers out of the box. So my thought was to use Coseva to filter the list and then write that back to a CSV format after parsing.
Here was the quick & dirty method I used to accomplish the task:
/**
* Write the parsed rows to a new CSV file.
*
* @return object \Coseva\CSV instance
*/
public function toCSV($filename)
{
if (!isset($this->_rows)) $this->parse();
$file = new SplFileObject($filename, 'w');
foreach ($this->_rows as $row) {
$file->fputcsv($row);
}
return $this;
}
Now I just need to make this a little more flexible...
Also, you might want to change __tostring
to let it use toCSV
I think I understand why you would suggest that. After all, toCSV
is writing the data to a file.
My only concern with it is, I don't think anyone would expect echo $csv;
to behave that way. Or at least, I don't think I would. I'd expect it to echo the contents to the browser. But maybe that's just me. :)
My bad, I actually didn't properly read the psuedo code. I would expect toCSV
to output CSV, rather than store it. Perhaps storeCSV
, save
or write
would be better method names, that could make use of a toCSV
to fetch the data as CSV.
How about toFile
or writeFile($filename)
?
I like save
personally.
Agreed