按标题名称(或索引)从 CSV 中删除列

时间:2021-02-26 16:07:49

标签: php csv thephpleague

我正在尝试使用 PHP 修改上传的 CSV 文件。更具体地说,我希望能够删除/删除列。

我有以下 CSV 文件(+10 万行):

,news_headline,news_article,news_category
0,"50-year-old problem of biology solved by Artificial Intelligence"," DeepMind's AI system .....",technology   

我想要做的是保存 CSV 文件的新副本,但仅限于列:news_headlinenews_category

这是我当前的设置

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);

以上代码输出:

,news_headline
0,"50-year-old problem of biology solved by Artificial Intelligence"

我期待的地方:

news_headline,news_category
"50-year-old problem of biology solved by Artificial Intelligence", Technology

0 个答案:

没有答案