Parsing a Text Input Field

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
Sponge
Forum Newbie
Posts: 3
Joined: Mon May 12, 2008 11:18 pm

Parsing a Text Input Field

Post by Sponge »

I know I've 'gotta be missing something simple here, but I've spent hours scouring Google, and have tried to figure this out on my own, but I'm just drawing blanks.

I need to write a script that basically converts a log output into something that I can import into a mySQL database. The log will be copy-pasted into a text field, and parsed from there. Although this won't be the final application, here's a basic example:
Log File:

Monday:
John (employee #5) 6 hours
Bill (employee #67) 2 hours
Steve (employee #12) 8 hours

Tuesday:
Jack (employee #22) 8 hours
John (employee #5) 2 hours
Bill (employee #67) 6 hours

Wednesday:
Steve (employee #12) 8 hours
Jack (employee #22) 8 hours
----
The script needs to take an input like that and create database rows with just two columns, Employee Name and Time Worked. Up to this point, I know how the script will work. However, it needs to combine all instances of an employee's name into a single row, and I'm not sure how to do that.

For example, the final result in the database will be (Name and then Time):
John 8
Bill 8
Steve 16
Jack 16

Thanks,

Adam
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Parsing a Text Input Field

Post by Eran »

Something like this perhaps:

Code: Select all

 
$handle = fopen(/employees/file/here, "r");
if ($handle) {
    $employees = array();
    while (!feof($handle)) {
        $line = explode(' ',fgets($handle, 4096));
        if(count($line) == 5) {
            $name = $line[0];
            if(isset($employees[$name])) {
                  $employees[$name] += $line[3];
            } else {
                  $employees[$name] = $line[3];
            }
        }
    }
    fclose($handle);
}
 
It assumes white spaces are exactly as you described
Post Reply