Member Avatar for Dukane

I'm trying to process a text file saved in the directory below where the PHP script is running.

First, it lists all of the files in the directory, skipping over . and .. Finally, it attempts to get a file handle for each file one at a time and then read the CSV contents for each of the files.

<?php
	clearstatcache();
	echo "Get contents of the canteen directory.<br>";
	$path = "./canteen/";
	$dir = opendir($path);
	while ($file = readdir($dir)) {
			if (is_file("$path" . "$file")) {
				$files[] = $file;
				echo $file;
				echo "<br>";
			}
	}
	
	echo "<br>Read each file and show output.<br>";
	foreach ($files as $file) {
		$path = "./canteen/$file";
		echo "$path<br>";
		
		//Try getting a handle.
		$fp = fopen($path, 'R');
		while ($line = fgetcsv($fp, 0, ',', '"')) {
			print_r($line);
		}
		fclose($fp);
	}

?>

However, the program dies with these errors in my server log:
[10-Aug-2008 17:45:15] PHP Warning: fopen(./canteen/0000999.TXT): failed to open stream: Undefined error: 0 in /my/debug.php on line 20
[10-Aug-2008 17:45:15] PHP Warning: fgetcsv(): supplied argument is not a valid stream resource in /my/debug.php on line 21
[10-Aug-2008 17:45:15] PHP Warning: fclose(): supplied argument is not a valid stream resource in /my/debug.php on line 24

I know the files exist, because I've deleted them and got a DIFFERENT error message (file does not exist). Put them back and now I'm getting this "undefined" error message. Please help! How can I fix the issue?

Recommended Answers

All 2 Replies

Change the mode parameter on line 20 to r:

$fp = fopen($path, 'R');

should be:

$fp = fopen($path, 'r');
commented: excellent, quick solution! thanks +2
Member Avatar for Dukane

That did it! Thank you! Guess my PHP book has a typo!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.