Search code examples
phptext

Reading .txt files with PHP and store information into variables


I have a two .txt files that I need to read. The content of the two files is below

log.txt

2013/04/20 01:08:11

and

data.txt

MANUFACTURER: SISYSTEM
MODELNAME: DX1
BIRTHDATE: 19710108
SEX: M

For log.txt i need to store the date from the first line and save it into mySQL database.

For data.txt i need to store information from each line into variables. i.e:

$manufacturer = SISYSTEM;
$modelname = DX1;
$birthdate =  19710108;
$sex = M;

For log.txt i can simply just read the first line using fget and store into one variable. However, for data.text, I am having trouble figuring out how to store multiple variables inside the loop. Here's what I have so far, but I don't know how to assign the values into new variables each time it goes through the while loop. Any help is appreciated!

<?PHP

$file_handle = fopen("data.txt", "r");

while (!feof($file_handle) ) {

   $line_of_text = fgets($file_handle);
   $parts = explode(':', trim($line_of_text) );


}

fclose($file_handle);

?>

Solution

  • Why do you need them in variables? An associative array ("map") is the cleaner approach

    $result = array();
      // Your loop -->
      $parts = array_map('trim', explode(':', $line_of_text, 2)));
      $result[$parts[0]] = $parts[1];