Add a comma to the end of each line using php

I have a csv file with 1 email id on each line. I want to add a 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 specific function for this?

UPDATE I want this so that I can build an array from it in javascript.

I will upload the csv file using php and then print it in js.

how

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

So, I get something like this.

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

Or is there a better way to do this?

+5
source share
5 answers

Why not use csv special features?

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

csv, , javascript, :

$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).'");';
+2
$lines = file('file.csv');
foreach ( $lines as & $line ) {
    $line .= ',';
}
file_put_contents('file.new.csv', implode(PHP_EOL, $lines));

- ,

+5
<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
    $line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
+2

$csv = str_replace("\n", ",\n", $csv);
+2

, csv, fgetcsv, json_encode(). , javascript. .

, , utf8_encode . utf8, json_encode barf.

php.net , .

+2

All Articles