I am trying to modify uploaded CSV files using PHP. More specifically, I want to be able to drop/delete columns.
I have the below CSV file (+100k rows):
,news_headline,news_article,news_category
0,"50-year-old problem of biology solved by Artificial Intelligence"," DeepMind's AI system .....",technology
What I want to do, is to save a new copy of the CSV file, but only with the columns: news_headline
and news_category
.
This is my current setup
use League\Csv\Reader;
use League\Csv\Writer;
//Read in current file.
$path = 'data.csv';
$reader = Reader::createFromPath($path);
$headers = ['news_headline', 'news_category'];
$records = $reader->getRecords($headers);
//Create a new file (override)
$writer = Writer::createFromPath($path);
//Insert new records
$writer->insertAll($records);
The above code outputs:
,news_headline
0,"50-year-old problem of biology solved by Artificial Intelligence"
Where I was expecting:
news_headline,news_category
"50-year-old problem of biology solved by Artificial Intelligence", Technology