6

I am having a csv file with 1 email id in each line. I want to add comma after each email id. I want to add a comma to the end of each line using php. How can i do this? Is there a particular function for that?

UPDATE I want this so that I can construct an array out of it in javascript.

I will be loading the csv file using php and then printing it in my js.

Like

var myCars=[<?php print $csv; ?>]; 

So that I acheive something like this.

var myCars=["Saab@gmail.com","Volvo@gmail.com","BMW@gmail.com"];

Or is there a better way to do this?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
esafwan
  • 17,311
  • 33
  • 107
  • 166

5 Answers5

5
$lines = file('file.csv');
foreach ( $lines as & $line ) {
    $line .= ',';
}
file_put_contents('file.new.csv', implode(PHP_EOL, $lines));

something like that should do, cheers

smassey
  • 5,875
  • 24
  • 37
3
<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
    $line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
smassey
  • 5,875
  • 24
  • 37
  • 1
    after reading your last update, i would say to add this for the JS, you need to remove the last trailing comma from the last line else the array will break in JS: var myCars=[]; – smassey Apr 06 '12 at 13:50
2

Why not use the csv-specific functions?

$old = fopen('file.csv','r');
$new = fopen('new.csv','w+');
while($line = fgetcsv($old))
{
    fputcsv($new,$line);
}
fclose($old);
fclose($new);

The above code will write a new csv, line per line, but if you just want to generate a javascript array, why not do this:

$file = fopen ('file.csv','r');
$all = array();
while($line = fgetcsv($file))
{
    $all[] = $line[0];//if there is only 1 field/line
    $all = array_merge($all,$line);//if multiple
}
fclose($file);
$js_array = '["'.implode('",',$all).'"];';
//or, the way I'd advise against, but good for multi-dimensional, assoc arrays
echo 'var array = JSON.parse("'.json_encode($all).'");';
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
2

why not just

$csv = str_replace("\n", ",\n", $csv);
kodisha
  • 1,074
  • 13
  • 24
2

Instead of echoing an entire csv string, you can import the file to an array using the fgetcsv function, then echo it out using json_encode(). That way you're sure to get a valid javascript array. It will also quote and encode any strings for you.

Oh, remember to run the array through some iterator which will run utf8_encode on all strings. If you have invalid utf8 characters, json_encode will barf.

There are plenty of examples on php.net of doing the different parts of this, but I can provide some examples if needed.

Gordon Forsythe
  • 356
  • 3
  • 7