Php Writing to csv file

By | 1st May 2011

In this code am taking in a variable from a dynamic form($search). The variable is 10 random unique numbers. It was put into the form from a text/csv file.

In this I need to write each line of the text/csv file into an array except the $search number, delete the contents of the file & write the contents of that array into the initial text file.

The $search variable is always going to be in the text file.

The text file is stuuctured as one number per line….

1234567890
2234567890
3334567890
4444567890

the code being used is:

<?

$search = $_POST[‘used’];

$file = “actn.csv”;
$f = fopen($file, “r+”);//file pointer

$ammount = count(file($file));// ammount lines/numbers in file

$i = 0;

While(!(feof($f)))

{

$line = fgets($f, 512);// get line

If( $line == $search ) // if line is equal to number passed ignore/dont add to array
{
echo “The number $search has been used.<br><br>”;
}

else
{
$i++;
$ctns[$i] = $line; // if not equal add to array
}

}

ftruncate($f,0); // delete content of text file

for ($i=1; $i < $ammount; $i++)
{
fwrite($f, $ctns[$i]); //write ctn array data to file
}

fclose($f);

?>

The problem at the moment is that when writing to the first line of the text file or the array(?) it produces alot of null charachters and adds to them each time.

i.e.

0123456789
1123456789
2223456789
3333456789

Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *