PHP - How to explode() lines from text file in to an array?

1.6k views Asked by At

This is what I'm trying to do:

  • I have a text file called member.log
  • ADD THE TOTAL amount of outstanding payments from each member-210.00 etc, Eg: inactive : [2007-04-01 08:42:21] "home/club/member" 210.00 "r-200"

  • To me it makes seems that I would need to separate the different parts of record so that I can target the [key] that correspondes to the amount 210.00, etc

  • I thought to do this with explode() but as I'm not passing a string to explode() I am getting an error: Warning: explode() expects parameter 2 to be string, array given in /home/mauri210/public_html/lfctribe.com/index.php on line 25

How can I solve this so that I can add up the total for each line?

Here is my php:

<?php
//Open the dir 
$dirhandle = opendir('/home/mauri210/public_html/lfctribe.com/data');

//Open file 
$file = fopen('/home/mauri210/public_html/lfctribe.com/data/members.log', 'r');

//Declare array 
$arrFile = array();

//Add each line of file in to array while not EOF 
while (!feof($file)) {
    $arrFile[] = fgets($file);

    //explode 
    $exarrFile = explode(' ', $arrFile);
}

var_dump($exarrFile);
?>

Here is contents of members.log :

inactive : [2007-04-01 08:42:21] "home/club/member" 210.00 "r-200"
inactive : [2008-08-01 05:02:20] "home/club/staff" 25.00 "r-200"
active : [2010-08-11 10:12:20] "home/club/member" 210.00 "r-500"
inactive : [2010-01-02 11:12:33] "home/premier/member" 250.00 "r-200"
active : [2013-03-04 10:02:30] "home/premier/member" 250.00 "r-800"
active : [2011-09-14 15:02:55] "home/premier/member" 250.00 "r-100"
4

There are 4 answers

1
Hakem On

You'll be needing this I guess

$items= preg_split('/[,\s]+/', $yourline);
0
Jakir Hossain On
    while (!feof($file)) {
        $arr_file = fgets($file);
        $arrFile[] = fgets($file);

        //explode 
        $exarrFile = explode(' ', $arr_file);
    }
var_dump($exarrFile);
0
Maurice Greenland On

I think I have solved this problem. I've tested with the small amount of sample data and seems to work. Here is my updated code:

    <?php


//Open the dir 
    $dirhandle = opendir('/home/mauri210/public_html/lfctribe.com/data');

//Open file 
    $file = fopen('/home/mauri210/public_html/lfctribe.com/data/members.log', 'r');

//List contents of file 

    while (($contents = fgets($file)) !== false) {

    $parts = explode(" ", $contents);
    $total = $total + $parts[5];
    }

    var_dump($parts);

    echo "this is key 5 $total";
?>
0
Akshay Hegde On

Try something like this

  $sum=0;
  foreach(file("path/to/file") as $line )
  {
      $fields=explode (" ", $line);
      $sum += $fields[count($fields)-1];
   }
      echo $sum;