简体   繁体   English

PHP从CSV中删除列

[英]PHP Remove columns from csv

I need to remove some columns and the first row from a csv and put the result in a new csv file. 我需要从csv中删除一些列和第一行,并将结果放入新的csv文件中。 I tried already with some sugesstions found here on stack, but none of them will work for me. 我已经尝试过在堆栈上找到一些建议,但没有一个对我有用。 My csv has 9 columns but i only need 5 of them. 我的csv有9列,但我只需要5列。 The best found solution here to remove the columns seems to be the one i will post below, but i only get commas in the result file and some where some data. 在这里找到删除列的最佳解决方案似乎是我将在下面发布的解决方案,但是我只在结果文件和某些数据中得到逗号。 The data in my csv are spararted with ';' 我的csv中的数据带有';'标记 I hope any one can help me. 我希望任何人都能帮助我。

Here is the code i played with: 这是我玩过的代码:

<?php
 $input = 'gesamtbestand.csv';
 $output = 'mw-stock.csv';

 if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');

while (false !== ($data = fgetcsv($ih))) {
    // this is where you build your new row
    $outputData = array($data[1], $data[2], $data[4], $data[5], $data[8]);
    fputcsv($oh, $outputData);
}

fclose($ih);
fclose($oh);
}

The default delimiter for fgetcsv is , as you can see in php manual http://php.net/manual/en/function.fgetcsv.php fgetcsv的默认分隔符是,如您在php手册http://php.net/manual/en/function.fgetcsv.php中所见

If your csv file uses ; 如果您的csv文件使用; for delimiter then you should change the line 对于定界符,则应更改行

while (false !== ($data = fgetcsv($ih))) {

to

while (false !== ($data = fgetcsv($ih, 0, ";"))) {

The default enclosure is " 默认附件为“

if you don't use an enclosure in your data then you should change the line to 如果您未在数据中使用附件,则应将行更改为

while (false !== ($data = fgetcsv($ih, 0, ";", ""))) {

As for excluding the first entry of the csv file you can do this 至于排除csv文件的第一个条目,您可以执行此操作

$i=0;
while (false !== ($data = fgetcsv($ih))) {
    // this is where you build your new row
    if ($i!=0){
        $outputData = array($data[1], $data[2], $data[4], $data[5], $data[8]);
        fputcsv($oh, $outputData);
    }
$i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM