Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a comma to the end of each line using php

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=["[email protected]","[email protected]","[email protected]"];

Or is there a better way to do this?

like image 440
esafwan Avatar asked Apr 06 '12 13:04

esafwan


2 Answers

<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
    $line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
like image 59
smassey Avatar answered Nov 06 '22 08:11

smassey


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).'");';
like image 2
Elias Van Ootegem Avatar answered Nov 06 '22 09:11

Elias Van Ootegem