Explode on a file?

Hello,

I have a script which reads a file in a directory and parses it into a MYSQL database table and it works well.

However, there is a load of junk text in the beginning of the file, so I want it to start reading the file, find the word “Files” in the array then process everything after that.



<?
/* Define and Open the Directory */
$path    = '/home/******/folder/';
$dir    = opendir($path);

/* Loop through the directory using a while loop if $dir exists */
while (false !== ($file = readdir($dir))) {
    
// suck the file into a line-by-line array
$lines = file($path.$file);
print_r($lines);

//* So at this point the data is held in a $lines array
//* But this is where I am stuck as at the start of the file there is a load of Junk text I do not want to parse.  
//* So Want to here run a explode to find the word "Files" in the array as everything after this is fine
//* But am unsure how to do this
// *Then process everything after the word "files" this using foreach below


//Run foreach (this bit is fine, no problems here)
foreach ( $lines as $line ) {
    $val = trim ($line); 
    $array = explode (',', $val); //Explode on the comma
	
    //Stick in a list rather than $array[0], $array[1] etc...
	list($name1,$name2,$name3) = $array;
	
          $sql = "INSERT INTO test (name1,name2,name3) VALUES ('$name1','$name2','$name3')";
          $query = mysql_query($sql) or die(mysql_error());

  
} //End Foreach 

} //End Reading File

?>


Can anyone kindly help?

Thanks

Yes, that makes sense! I see what you mean now thanks all!

Thanks, but I don’t understand. Can you post an example please?

I am not sure what exactly you are wanting to do but consider the following code once to check if the line has word ‘Files’ in it and then makes the variable $find_line = true; and until the variable is true it will not execute rest of the lines:


//Run foreach (this bit is fine, no problems here)
$find_line = false;
foreach ( $lines as $line ) { 
    if(strpos($line, 'Files')){
        $find_line = true;
    }
    if($find_line){
        $val = trim ($line); 
        $array = explode (',', $val); //Explode on the comma 
         
        //Stick in a list rather than $array[0], $array[1] etc... 
        list($name1,$name2,$name3) = $array; 
         
        $sql = "INSERT INTO test (name1,name2,name3) VALUES ('$name1','$name2','$name3')"; 
        $query = mysql_query($sql) or die(mysql_error());
    }
} //End Foreach

You don’t need to explode, just strpos() each line for “target”