php parsing/read text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
eian@php
Forum Newbie
Posts: 7
Joined: Sat Aug 21, 2010 10:22 am

php parsing/read text file

Post by eian@php »

Hi to All! I have a problem on handling my text file..
My Text File format is this

1 romeo perez 8877 2010-07-07 abc1
2 nick mayo 7686 2010-07-07 abc2
3 mark yu 5456 2010-07-07 abc3
4 karm santos 3432 2010-07-07 abc4

I want to be able to insert the 2nd and 3rd field to the database as one and the next fields must be saved to their respective fields individually..
For example:
rome perez should be save to database as one and so on..romeo and perez is separated by a space.

Here is my code:

<?php
mysql_connect("localhost","root","");
mysql_select_db("personss");

$textFileName = $_POST['textFileName'];

$myFile = "$textFileName";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$person = explode("\r\n", $theData);
$count = 0;

foreach($person as $i => $line) {
$nameParts = explode(" ", $line);

//mp = array_filter(explode(' ',$person));
$q = "insert into logged (id, name, num, datess, letters) values ('" . implode("','",$nameParts) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
$nameParts = explode("", $line);
$count++;
}
?>
Please help me fix this..
Attachments
This the format should be:<br />the 2nd and 3rd fields are treated as one separated by a space
This the format should be:
the 2nd and 3rd fields are treated as one separated by a space
1.jpg (15.57 KiB) Viewed 219 times
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: php parsing/read text file

Post by Jonah Bron »

Please always surround your code with [syntax] tags (press the PHP Code button).

Code: Select all

foreach($person as $i => $line) {
    $nameParts = explode(" ", $line);

    // Notice this part
    $nameParts[1] = $nameParts[1] . ' ' . $nameParts[2];
    unset($nameParts[2]);

    //mp = array_filter(explode(' ',$person));
    $q = "insert into logged (id, name, num, datess, letters) values ('" . implode("','",$nameParts) . "')";
This just puts the third and second elements of the array into the second together, and deletes the second.
eian@php
Forum Newbie
Posts: 7
Joined: Sat Aug 21, 2010 10:22 am

Re: php parsing/read text file

Post by eian@php »

Thank you very much Sir.. You helped me a lot.. im still new in php.. Tnx vm.
Post Reply