By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,512 Members | 3,790 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,512 IT Pros & Developers. It's quick & easy.

fgetcsv returns false in dynamic read vs. hard-coded read ??

P: n/a
I am working with directories in PHP for the first time. I have code
that I've changed multiple times to try different things. I would think
this is pretty standard fare so I'm not sure why I can't seem to get it
right.

What I would like to see happen:

The code opens the directory and loops through the files, opening them
and processing them.

What is happening:

If I hard code the name of one particular file (it is always the same
file) in my test setting, fgetcsv does not return false and the code
runs fine. The file is parsed and all is well. However, if I let the
code open a directory and then loop through the files, this one
particular txt file does not work. For debug purposes, I have it
displaying each file name and it can display the name, it just won't
process it.

I've even tried setting a for loop and hard coding each file name
(since right now I know the names - I won't in the future) and the file
is processed. It is only when it is set to my $file var dynamically
rather than being hard coded.

Here is the code:
$handle_dir = opendir('../directory_name');
/* loop over the directory. */
$countfile=0;
while (false !== ($file = readdir($handle_dir))) {
$countfile++;
$filevalues = "";
//Skip the first two files that where found because they are
"." and ".."
if ($countfile 2) {
//echo $file;
//begin loop through each file name
$handle = fopen($file, "r");
echo "Filename is: $file<BR>";//at this point the
code can print the file name
if (false == ($filevalues =
fgetcsv($handle,6021,','))){
echo 'problems<br>';//for one particular file,
this always displays
}
while (false !== ($filevalues =
fgetcsv($handle,6021,','))){
echo 'I hit the loop: '.$file.'<br />';
//processing code here
}

}

}

closedir($handle_dir);

here is the hard-coded version:
for ($i=0;$i < 2; $i++){
switch ($i) {
case 0:
$file = 'filename.csv';
break;
case 1:
$file = 'filename2.csv';
break;
default:
die('Out of loop');
break;
}
$handle = fopen($file, "r");
echo "Filename is: $file<BR>";//at this point the
code can print the file name
if (false == ($filevalues =
fgetcsv($handle,6021,','))){
echo 'problems<br>';//for one particular file,
this always displays
}
while (false !== ($filevalues =
fgetcsv($handle,6021,','))){
echo 'I hit the loop: '.$file.'<br />';
//processing code here
}

}

closedir($handle_dir);

I appreciate any help.

Sep 20 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.