Re: fgetcsv

From: Date: Wed, 09 Jan 2008 22:59:21 +0000
Subject: Re: fgetcsv
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-266980@lists.php.net to get a copy of this message
Danny Brow wrote:
Hi Everyone, I'm trying to compare a value to the first field in a csv fILE (example of the data below). Using while takes too long and I can't figure out how to compare just one row at a time. I've tried some variations of the following. //Common for all trials $demoID = fopen("newDemoID.csv", "r");; $ID = "43"; $data = fgetcsv($demoID); First try with while: /* while ($data) {
        if ($data[0] == $wolfID) {
                print $data[1] . "," . $data[2] . "," . $data[3] .
".\n";
        }
} */ Takes for every. I can't use just the below because it only compares the first row. /* if ($data[0] == $wolfID) {
       print $data[1] . "," . $data[2] . "," . $data[3] . ".\n";
} */ I know this is simple, but I've hit codes block due to lack of sleep. Thanks, Dan Sample Data:
5,1,"Smith","Myrtle" 6,2,"Smith","Carita" 7,3,"Smith","Paul" 8,4,"Smith","Donald"
Maybe try something like this. <?php //Common for all trials $fh = fopen("newDemoID.csv", "r");; # What we are looking for $ID = "43"; # check for valid handle if ( is_resource($fh) ) { # Loop through file handler # if we get data, we check it # if/when we get false, we break out of the while loop while ( ($data = fgetcsv($fh) ) !== false ) { # Check for the value you are looking for.
	        if ( $data[0] == $ID ) {
# Obvious...
	                echo "{$data[1]},{$data[2]},{$data[3]}\n";
	        }
} fclose($fh); } ?> -- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare

« previous php.general (#266980) next »