tags:

views:

277

answers:

3

Hello all,

I have a text file (its comma delimited with some fields wrapped around in double quotes) when I parse through it using this:

if (($handle = fopen('C:\tester\fake.txt', "r")) !== FALSE) {
    while (($data = fgetcsv($handle, ",")) !== FALSE) {
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

It shows each field not to have quotes, does the fgetcsv remove this automatically?

How can I get it to show fields that do not have quotes and add quotes to them and then save the file? Possible?

Thanks all

Update

I have just tried the fputcsv and I find the file written doesn't have quotes around the fields, only very few, less than the initial file had! What am I doing wrong?

$row = 1;
$newfile = fopen('C:\new-file.txt', "w");

if (($handle = fopen('C:\fake.txt', "r")) !== FALSE) {
    while (($data = fgetcsv($handle, ",")) !== FALSE) {
        $num = count($data);
            fputcsv($newfile, $data, ',', '"');
    }
    fclose($handle);
    fclose($newfile);
}
+1  A: 

The quotes are part of the CSV file format (quotes around fields that contains , or newlines), therefore fgetcvs will (and is expected to) remove them.

Emil Vikström
Is there another way I can parse this and see the quotes so that I can add quotes to fields that do not have quotes?
Abs
Just add quoets to all the fields. You will not get any field with quotes around it.
Emil Vikström
None of the fields will have quotes after being extracted with fgetcsv, unless the quotes were part of the original string and assuming those were properly escaped before being added to the csv file. When you add them to a file, use fputcsv() and let php do the quoting. See the link in Jimmy Shelter's answer.If you want to inspect or parse the lines as they are written in your original file ("fake.txt"), put them into an array with file()
GZipp
+2  A: 

fgetcsv does remove the quotes.

With fputcsv you can write a cvs-file. It does have options regarding using quotes or not, but it will do the same for all fields.

Check http://www.php.net/fgetcsv and http://www.php.net/fputcsv

Jimmy Shelter
Jimmy's got it, read in your file with fgetcsv and then write a new version back out with fputcsv and you should have a file that's properly quoted.
Cryo
That's a good idea - but I was hoping to check through the text file first as some may be formatted properly already.
Abs
I've tried this, please see my update.
Abs
A: 

yes it removes the quotes because it assumes you want the data for the columns and the quotes arent part of the data. use fget instead.

prodigitalson