reading a txt file

I’ve seen many many tutorials about using fopen with the r argument. I’ve seen many where the code would search for a certain tag. But all of that’s opposite of what I’m needing to do.

The file is read by a piece of software written in c. All the lines are commented out with ; and after the last comment, thats where the software writes its data. 5 fields per line. The first section is numerical, the second is a password field, the last two are numerical representations of user level. Example would be:

; Comments
; Comments
; Comments
123456 password 12 12
234567 abcdef 3 2

as I said, each new line is different all the way to the end. I want to take this info and check it against a database, then either do nothing or update the file. Any suggestions on where to start?

Hi there,

This works for me, though it may be a tad messy with some pointless code. Let me know if you want me to look into a cleaner solution (not that dealing with txt files is particularly clean):
[php]<?php

$data = preg_grep(’/;.+/i’,file(‘BBuchanan.txt’),PREG_GREP_INVERT);
$comments = preg_grep(’/;.+/i’,file(‘BBuchanan.txt’));

foreach($data as $key => $contents)
{
$data[$key] = explode(’ ',trim($contents));
}

echo ‘

’;
print_r($data);
echo ‘
’;
/*
  • THE ABOVE RESULTS IN:
    Array
    (
    [0] => Array
    (
    [0] => 123456
    [1] => password
    [2] => 12
    [3] => 12

     )
    

    [1] => Array
    (
    [0] => 234567
    [1] => abcdef
    [2] => 3
    [3] => 2
    )
    )
    */

//database checks - make changes to relevant elements in the array

foreach($data as $key => $contents)
{
$data[$key] = implode(’ ',$contents);
}

$file = fopen(‘BBuchanan.txt’,‘w+’);
fwrite($file,implode(’’,$comments).implode("\n",$data));
fclose($file);

?>[/php]

Let me know how you get on

Sponsor our Newsletter | Privacy Policy | Terms of Service