Delete lines from CSV file

Hello

I have a CSV file sent by a stock company daily. I have a update function that takes that data from CSV and update a database. CSV has 50 columns, and about 10,000 Rows. And at the end of the CSV there are few INSTRUCTIONS.

Obviously, those instructions are not to be uploaded to the database, and thus need to be deleted once the file is uploaded.

So the instructions start with a heading INSTRUCTIONS
and then there are about 20-40 rows of instructions.

I want to have a function that will delete anything starting from INSTRUCTIONS will the end of file. Please guide me how to achieve this.

Thanks
Zeeshan

How does your function handle the CSV file?
Does it insert the data in the DB one row at a time? If so, you can check the heading of each line, and not insert the ones starting with INSTRUCTIONS.

CSV has 50 columns, and about 10,000 Rows.

if your file have 50 columns and 10,000 rows than you must have same structure in your database also so in any case if you dont have any column for instruction or whatever the unwanted data wont get stored in the database. thats what i think so.

I hope following is the code actually you needed.

if(isset($_POST['Submit'])=="Upload")
  {
    
$handle = fopen ("..\\..\\Book1.csv","r");
	   
	while ($data = fgetcsv ($handle, 1000, ",")) {
	            
	            $prod_id  =  $data[0];
	            $no_of_qt =  $data[1];
	            $notes    =  $data[2];
	            $prize    =  $data[3];
	            $b_id =     $data[4];
	     
	     
         $link1=mysql_connect("xxx", "xxx", "xxxx") or die(mysql_error());
				  		    	 // echo 'Connected successfully';
		    		mysql_select_db("xxx") or die(mysql_error());
	   $query1 = "INSERT INTO p_b (prod_id,no_of_qt,notes,prize,b_id) values ('".$prod_id."','".$no_of_qt."','".$notes."', '".$prize."','".$b_id."')";
	   $result1 = mysql_query($query1) or die('Query failed: ' . mysql_error());
	   }
	 }
	 }
	  fclose ($handle); 
	  
	} else{
	echo "please upload your file.";
	}
}


while ($cols = fgetcsv($fh)) {
    if (count($cols) === 50) {
        // use it
    }
}

if (count($cols) === 50) {

    // use it

}

crmalibu, do you really think he/she has to count the column here?

just want to know about different logic.thats why asking this.

A basic idea, if you want to edit the actual CSV file, would be to look for the INSTRUCTIONS line and truncate the file to that point. For example:


$fp = fopen($file, 'r+');

// Locate the point in the file which is
// a line containing only "INSTRUCTIONS"
$cursor = FALSE;
while ( ! feof($fp))
{
	$line = fgets($fp);
	if (rtrim($line) == 'INSTRUCTIONS')
	{
		$cursor = ftell($fp) - strlen($line);
		break;
	}
}

// Truncate the file if the "INSTRUCTIONS" line was found
if ($cursor !== FALSE)
{
	ftruncate($fp, $cursor);
}

fclose($fp);


Hello Every one

Salathe, put the same login which I used !
That is the correct way out !

Thanks every one !

Regards