Forum Moderators: coopster

Message Too Old, No Replies

opening an existing csv file

         

wkpride

2:37 pm on Dec 30, 2009 (gmt 0)

10+ Year Member



Hi,

I have a an existing .csv file that I can open and read from, but when I use r+ or w, it will not open.

I get this error:
Warning: fopen(Gassaway Storm 12232009.csv) [function.fopen]: failed to open stream: Permission denied in C:\wamp\www\projects\Poles\write.php on line 33

Is it possible to open an existing .csv file? I'd like to clean the data and dump it into a db....

The code:
$row = 1;
if (($handle = fopen("Gassaway Storm 12232009.csv", "w")) !== FALSE)
{ while (($data = fgetcsv($handle, 1000, ",")) !== 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);
}

Thanks!
KP

rocknbil

7:09 pm on Dec 30, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This means it's an invalid path, or . . . your script doesn't have write permissions in that directory . . . or possible, reading from it and writing to it at the same time(?) Not even sure if you can do that.

wrap it in an is_writable() [us.php.net]. Move the file into a variable, you'll need to eventually anyway, specify a full path. Make sure permissions are set on that path.

Also it looks like your fclose is in the wrong place . . . closing inside the write block . . . and not sure how spaces in filenames will work out for you.

Last consideration, I'm not sure if you're opening and writing to the file at the same time, if you are, this may be a problem too. Open the file read in the data, then write to it - but you may want to write to a different file instead.

I also don't see an fwrite() . . . but get past this first . . .


$row = 1;
// Don't use your php directory to write to.
// make sure perm's on the dir are writable.
// Also note $delimiter; if/when you move to
// a linux environment the delimiter will be /, not \
$delimiter = '\';
$full_path= 'C:\wamp\www\projects\Poles\exports';
$csv = 'Gassaway Storm 12232009.csv';
$outfile = $full_path . $delimiter . 'outfile.csv';
$myfile = $full_path . $delimiter . $csv;
if (is_writable($outfile)) {
if (($handle = fopen("$outfile", "w")) !== FALSE) {
// Next line QUESTIONABLE, not sure you can do this.
// Get data first, or use different $handle. Changes applied above.
while (($data = fgetcsv($myfile, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row:</p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br>\n";
}
} // inner while
} // end fopen
fclose($handle); // NOW close file handle
} // end writable
else { echo "<p>OOPS! $outfile is not writable.</p>"; }