douci1851 2014-11-21 08:41
浏览 66
已采纳

PHP使用fputcsv CSV在每列的列中写入相同的数据

I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow There is not separator only a delimiter which is the semi colon.

I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.

So far it adds the new column with but I can't understand how to put the same value in each line for that column ?

<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?

if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
        $data[] = 'ExempleRow';
        $newCsvData[] = $data;
    }
    fclose($handle);
}

$handle = fopen('exemple.csv', 'w');

foreach ($newCsvData as $line) {
   fputcsv($handle, $line,';',' ');
}

fclose($handle);

?> 
  • 写回答

1条回答 默认 最新

  • dongyanzhui0524 2014-11-21 09:51
    关注

    If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.

    $handle = fopen('exemple.csv', 'w');
    $keys = false;
    
    foreach ($newCsvData as $line) {
       if ($keys === false) {
           //$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
           fputcsv($handle, array_keys($line), ';', '');
           $keys = true;
       }
       fputcsv($handle, $line,';',' ');
    }
    
    fclose($handle);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题