CSV到TSV(但只有第1和第3行)或表格

时间:2014-03-14 23:31:15

标签: javascript php csv

我有一个像这样的CSV文件:

Name,7680,Value,7684,7685,7688,7689,7690,7697,7698,7699,7700,7701,7702,7703,7704,7710,7711,7712,7733,7737
140101_130002,2,50948,1,21801,316,316,327,500,887,903,900,897,641,654,673,332,310,324,3,6,0,0
140101_133002,2,51046,1,21849,317,316,327,500,887,899,902,896,645,654,678,335,317,325,3,6,2,2
140101_134501,2,51096,1,21874,315,315,326,499,886,899,898,894,638,651,671,335,314,325,3,6,3,3   

第一行是名称,我想取第一个值和第三个值并使它们成为TSV或者至少将它们放在html表而不是所有值上。

例如我需要这个:

Name    Value

140101_130002   50948   
140101_133002   51046

请帮忙。

1 个答案:

答案 0 :(得分:0)

此代码可以满足您的需求。

    $csv_file = "yourfile.csv"; // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');
    $name_value=array();

    if(is_file($csv_file)){

        fgets($csvfile); // read and ignore the first line
//if you want to show "Name Value" at beginning of the table, just comment this line

        while (!feof($csvfile)){
            $data = fgetcsv($csvfile,4096,",");
            $name_value[]=array($data[0],$data[2]);
        }

        fclose($csvfile);

        echo "<table>";
            foreach($name_value as $data_to_show) {
                echo "<tr><td>".$data_to_show[0]."</td><td>".$data_to_show[1]."</td></tr>";
            }
        echo "</table>";
    }else die('File no good!');

它会回显一个表格,其中包含:

140101_130002   50948
140101_133002   51046
140101_134501   51096