using fputcsv()

using fputcsv()

am 08.11.2007 16:34:31 von shenoyvikram

New to PHP

I am trying to search through a csv file. when I match a string I want
to replace it using the fputcsv function. However, I always notice
there is an extra line inserted. I am using fseek to move file
pointer.
- does fputcsv replace or insert data into csv file?
Code below and example of problem also.
while( ($data = fgetcsv($fid, 1000, ",")) !== FALSE) {
if (strcmp ($data[0], $compare) == 0){
fseek ($fid,$offset_counter);
fputcsv($fid, $data1);
$offset_counter = ftell ($fid);
}

My starting file
11,11,11,11
22,22,22,22
33,33,33,33

The output I expect
11,11,11,11
33,22,22,22
33,33,33,33

The output I am getting
11,11,11,11
33,22,22,22

33,33,33,33

Re: using fputcsv()

am 08.11.2007 21:22:13 von Jerry Stuckle

shenoyvikram@yahoo.com wrote:
> New to PHP
>
> I am trying to search through a csv file. when I match a string I want
> to replace it using the fputcsv function. However, I always notice
> there is an extra line inserted. I am using fseek to move file
> pointer.
> - does fputcsv replace or insert data into csv file?
> Code below and example of problem also.
> while( ($data = fgetcsv($fid, 1000, ",")) !== FALSE) {
> if (strcmp ($data[0], $compare) == 0){
> fseek ($fid,$offset_counter);
> fputcsv($fid, $data1);
> $offset_counter = ftell ($fid);
> }
>
> My starting file
> 11,11,11,11
> 22,22,22,22
> 33,33,33,33
>
> The output I expect
> 11,11,11,11
> 33,22,22,22
> 33,33,33,33
>
> The output I am getting
> 11,11,11,11
> 33,22,22,22
>
> 33,33,33,33
>
>

You can't safely insert data into the file like this. You'll run into
even more problems if the the new line is of different size than the old
one.

What you need to do is read the whole file in and write it back out.
There are a couple of ways to do this. If it's a small file, you can
just read everything into an array then write it all out. For larger
files, you can read them in one line at a time and write them out to a
temporary file. Then when you're done, delete the original file and
rename the temporary one.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================