vinner Posted June 16, 2011 Share Posted June 16, 2011 Hello forum members, I am a beginner at programming and at PHP too. My objective is to read a CSV file check the initial two conditions for a match and then forward the user to a link Here is my CSV file php,26.06.2011,http://www.google.com java,26.06.2011,http://www.google.com This is the code that I've written. My problem is that the code does not read the entire contents of the CSV file. It reads the second line but not the first line. I'm a bit confused could someone help me <?php error_reporting(E_ALL|E_STRICT); ini_set("display_errors", "On"); $name_value=$_GET['query']; $fh = fopen('db.csv', 'r'); $now = date("d.m.Y"); $data=fgetcsv($fh); $name=$data[0]; $date=$data[1]; $url=$data[2]; while(list($name, $date, $url) = fgetcsv($fh)) { { if($name_value == $name AND $date>=$now) { header("Location: $url"); exit(); } else { echo "name is $name \t\t name 2 is $name_value<br>"; echo "date is $date \t\t now date is $now<br>"; echo "URL is $url"; } exit; } } ?> Quote Link to comment Share on other sites More sharing options...
WebStyles Posted June 16, 2011 Share Posted June 16, 2011 you can simply use file_get_contents() to read the file, then use explode() to break it up. something like this: $file = file_get_contents('csvfile.csv'); $lines = explode("\n",$file); foreach($lines as $line){ $data = explode(",",$line); $name = $data[0]; $something = $data[1]; //....etc... } I'm assuming 2 things here: 1. you file uses \n as the line break character 2. it is delimited by commas (as the name CSV emplies) Hope this helps. Quote Link to comment Share on other sites More sharing options...
xylex Posted June 16, 2011 Share Posted June 16, 2011 $data=fgetcsv($fh); $name=$data[0]; $date=$data[1]; $url=$data[2]; while(list($name, $date, $url) = fgetcsv($fh)) ?> Your bug is right there. Make sure you understand what fgetcsv() and list() are doing. Quote Link to comment Share on other sites More sharing options...
vinner Posted June 16, 2011 Author Share Posted June 16, 2011 Thank you forum members for your help after trial and error method I was able to come up with a working code <?php error_reporting(E_ALL|E_STRICT); ini_set("display_errors", "On"); $name_value=$_GET['query']; $fh = fopen('db.csv', 'r'); $now = date("d.m.Y"); $line = 1; if (($handle = fopen("db.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); $line++; for ($c=0; $c < $num; $c++) { if($name_value == $data[0] AND $data[1] >= $now) { header("Location: $data[2]"); exit(); } else { header("Location: http://localhost/x/client_unauthorized.html"); } } } fclose($handle); } ?> and I feel very happy for doing this on my own Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.