Jump to content

Reading csv file


Ache

Recommended Posts

I have a csv file that looks like: UniuqeID;firstname;lastnameA form lets the user set the UniuqeID ($prk)What I want is to read the csv file and put the data of the line that matches the UniuqeID in $userDataI have written the underneath code for it, but it is not working.Where am I going wrong?

	$fh = fopen("users.log", 'r');	while (!feof($fh))		{			$theData = fgets($fh);			if (stripos($theData,$prk) !== False)			{				$userData = fgetcsv($fh,";");			}		}	fclose($fh);

Link to comment
Share on other sites

I've never tried reading a file in just this combination. I THINK that when you call fgets() the file pointer gets advanced to the next line. So fgetcsv() will be reading the NEXT line, not the one you want.Again, I haven't tried this, but you might try str_getcsv($theData, ';') instead of fgetcsv();Should you also break out of the while loop once you have a successful match? No use in continuing the file read.Any reason you're not using a database like MySql? Same idea, but much simpler.

Link to comment
Share on other sites

Much simpler? Not for me. I just started learning php, so one thing at a time. Mysql will come after I decently know php :) But this morning I woke up, looked at the code and thought.... What a mess. But I also saw something else. A rather easy way to do it.

// Get the user data	$fh = fopen("users.log", 'r');	while (!feof($fh))		{		$tempData = fgetcsv($fh,",");		if ($tempData[0] == $prk)			{			$userData = $tempData;			}		}	fclose($fh);

It may not be the 'cleanest' code, but at least it is working. Ok, it still reads the entire csv file, but at least it graps the correct data (line)

Link to comment
Share on other sites

To stop the loop, you just have to add "break;" below "$userData = $tempData;".That'll save you quite a bit of overhead if your "users.log" file becomes large.[EDIT] I should have included a code sample. Here:

		if ($tempData[0] == $prk)			{			$userData = $tempData;			break;			}

-Jason

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...