hi i have a text file with 5 fields per line.. i want to parse these fields and save it to mysql database table this is the format of my text file: joe 1234asdc 7:51:00 2010-08-21 hi john 543kjkj 7:45:00 2010-08-21 hello rey 675jhgj 7:40:00 2010-08-21 nice the fields are separated by spaces.. anyone help me on how to do the exact coding..
Hm, maybe explode( ) function will do the trick. $yeh = explode(" ", $string); PHP: $yeh[0] is "joe" $yeh[1] is "1234asdc" $yeh[2] is "7:51:00" $yeh[3] is "2010-08-21" $yeh[4] is "hi" Code (markup):
<?php $lines = file('textfile.txt'); foreach ($lines as $line) { $chunks = explode(' ', $line); foreach($chunks as $chunk) { //do a mysql insert query with $chunk... echo $chunk.'<br />'; } } ?> PHP:
It looks to me as though you have a line-break delimited text file with space delimited lines. You can use a multi-dimensional array like the first poster said except it's a little more than he explained if you want to have your lines properly sorted out. You will have to delimit the lines first into a single array each and then from there break that array further into fields. Below is how that will work. <?php /** * Handle should be all the content you read from a text file * using whatever method. If you have the variable named differently, * just delete this var definition and change the other handle vars in this code * snippet */ $handle = "joe 1234asdc 7:51:00 2010-08-21 hi john 543kjkj 7:45:00 2010-08-21 hello rey 675jhgj 7:40:00 2010-08-21 nice"; $lines = array(); // Init empty array $fields = array(); // Init empty array $lines = explode("\n",$handle); // Get each line for($i=0;$i<count($lines);$i++) // Loop for each line $fields[$i] = explode(" ",$lines[$i]); // Store the data by your " " break print"<pre>";print_r($lines);print_r($fields); // Print the array structures print $fields[0][0]; // Example usage of multi-dimensional array. This takes the 0 array (with the 5 fields in it) // and it's value at key 0. ?> PHP: it should give you this output Array ( [0] => joe 1234asdc 7:51:00 2010-08-21 hi [1] => john 543kjkj 7:45:00 2010-08-21 hello [2] => rey 675jhgj 7:40:00 2010-08-21 nice ) Array ( [0] => Array ( [0] => joe [1] => 1234asdc [2] => 7:51:00 [3] => 2010-08-21 [4] => hi ) [1] => Array ( [0] => john [1] => 543kjkj [2] => 7:45:00 [3] => 2010-08-21 [4] => hello ) [2] => Array ( [0] => rey [1] => 675jhgj [2] => 7:40:00 [3] => 2010-08-21 [4] => nice ) ) joe Code (markup): Good luck! Regards, Dennis M.