Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add columns to CSV using PHP

Tags:

php

I need to add columns to an existing csv file ,but i can't find any solution to the problem.I have used "\t" and chr(9) to create columns but no success so please help me by providing me the right solution if any one can

like image 275
Ankur Mukherjee Avatar asked Jul 30 '10 11:07

Ankur Mukherjee


People also ask

How to add Column in Csv file using PHP?

php $newCsvData = array(); if (($handle = fopen("test. csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $data[] = 'New Column'; $newCsvData[] = $data; } fclose($handle); } $handle = fopen('test.

How can I get the number of columns in a csv file in PHP?

If I understand, you simply need count($line) , because fgetcsv() has returned an array representing one row from the CSV file. The array's count() is therefore the number of source columns.


1 Answers

Try this, and have a look at fgetcsv() and fputcsv() in the manual

<?php
$newCsvData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = 'New Column';
        $newCsvData[] = $data;
    }
    fclose($handle);
}

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

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

fclose($handle);

?> 
like image 72
Phliplip Avatar answered Oct 15 '22 00:10

Phliplip