Reputation: 21
Hey everyone I am learning some php and manipulating some csv files here. I'm creating a random key generator for some courses. Basically I am adding a new column with the keys for a course.
I have managed to do this. However when I run my script I get an extra row being read and a key generated for that. Example if I have 3 courses A,B,C then 4 keys would be generated and added to the csv.
Can I have some help or tips on reading and writing to a csv?
<?php
$file= fopen("input.csv","r");
$output=fopen("output.csv","w");
function gen_keys($length=10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
//echo gen_keys();
$list=array();
while(!feof($file))
{
//print_r(fgetcsv($file));
$list=fgetcsv($file);
//$list=array_filter($list);
$list[]=gen_keys();
echo "<br />";
print_r($list);
fputcsv($output, $list);
//print_r(fgetcsv($output));
}
fclose($file);
fclose($output);?>
Input : comp1400
comp2000
info2425
eng1234
Upvotes: 0
Views: 780
Reputation: 3563
<?php
$infp = fopen("in.csv", "r");
$outfp = fopen("out.csv", "w");
while(!feof($infp)) {
$list = fgetcsv($infp);
// change $list and write to output
fputcsv($outfp, $list);
}
Upvotes: 0
Reputation: 1668
Here is updated and working version:
$list=fgetcsv($file);
if (!empty($list)) {
//$list=array_filter($list);
$list[]=gen_keys();
echo "<br />";
print_r($list);
fputcsv($output, $list);
}
Please note line with if (!empty($list)) {
it checks if we have any imput.
More information about empty()
in documentation.
Upvotes: 1