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

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"

while (!feof($file)) {
$arr_file = fgets($file);
$arrFile[] = fgets($file);
//explode
$exarrFile = explode(' ', $arr_file);
}
var_dump($exarrFile);

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

You'll be needing this I guess
$items= preg_split('/[,\s]+/', $yourline);

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";
?>

Related

How to remove everything after a space in each of my array objects in PHP?

I have two arrays containing letters and numbers for each array object. example: "Matthew 20897". I want to delete the numbers from every array object so I can compare both arrays and see if they have any words/names in common. I tried doing an explode to get rid of the space but I get an error saying the explode() expects parameter 2 to be a string.
Below is the code I have so far:
<?php
//simple read file and print
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$word = fgets($connectionBoy); //read a record
$word = rtrim($word); //gets rid of end of record char
$boy[] = $word;
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$word2 = fgets($connectionGirl); //read a record
$word2 = rtrim($word2); //gets rid of end of record char
$girl[] = $word2;
}
fclose($connectionBoy);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$itemBoy = explode(" ",$boy);
$itemGirl = explode(" ",$girl);
$result =array_intersect($itemBoy,$itemGirl);
print_r($result);
Also, both arrays have 1000 records stored in them so I would have to remove everything after the space for all items in both arrays.
Use rtrim().
echo rtrim(' Removendo Espaços ');
https://www.php.net/manual/pt_BR/function.rtrim.php
http://www.mauricioprogramador.com.br/posts/remover-espacos-php-trim-ltrim-e-rtrim
From the docs:
explode — Split a string by a string
explode takes a string and splits it into an array. $boy and $girl are already arrays.
If I understand what you're trying to do, you could do get rid of the numbers inside your loops doing something like this:
$splitWord2 = explode(' ', $word2);
$girl[] = $splitWord2[0];
From your code I'm seeing you are using explode function in the wrong place. It should be in the while loop as string should be exploded there to get the first word of name.I have updated your code.
<?php
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$line = fgets($connectionBoy); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$boy[] = $parts[0];
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$line = fgets($connectionGirl); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$girl[] = $parts[0];
}
fclose($connectionBoy);
fclose($connectionGirl);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$result =array_intersect($boy,$girl);
print_r($result);
?>

How to read a file and sum the number of that file in php

Let's say you have a file with the following structure: txt format
"id,name,value
1,Dan,150
2,Peter,300
3,Mark,400
4,Victor,600"
This function I used to read the file :
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
fclose($userfileInfo);
}
Output:
"id,name,value 1,Dan,150 2,Peter,300 3,Mark,400 4,Victor,600"
How i will seperate 150, 300, 400, 600 and sum them in php.
It's a csv file, you can explode each line with , and sum the last item except the first header line.
$lines = file($file_path);
$lines = array_map(function($v){return explode(",",$v);},array_slice($lines,1));
echo array_sum(array_column($lines,2)) . PHP_EOL;
Try to use preg_match_all and RegEx
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
preg_match_all('/\d+,.+,(\d+)/', $theData, $output);
$sum = 0;
foreach($output[1] as $value){
$sum = $sum + (int) $value;
};
//echo "Sum :".$sum;
fclose($userfileInfo);
}
You can use fgets function to read it line by it. Then you can easily use explode function to change the line into array. The last index in the array is your desired value.
something like below:
$theData = fopen("peopleInformation.txt", "rw");
fgets($theData); //skip the header.
$sum = 0;
while (! feof ($my_file))
{
$line = fgets($theData);
$array_val = explode($line);
$sum += (int)end($array_val);
}

php data from text file to multidimensional array doesnt work but no console errors

I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:
$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
$line_result = $line;
}
echo $line;
I have to calculate the result of $line - 1 and echo that result.
But when i do:
$line = $line - 1;
Then it shows $line - 1 and doesn't actually do the calculation.
Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:
$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;
Try replacing
$line = $line - 1;
echo $line
with
$line = ($line -1);
echo $line
This will print 19 instead of 20-1.
I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...
http://php.net/manual/en/function.intval.php
Try this:
$fin = #fopen("path to file", "r");
if ($fin) {
while (!feof($fin)) {
$buffer = fgets($fin);
}
fclose($fin);
}

PHP while looping through arrays

Hy everyone, I'm having trouble with properly nesting while loops to read from 2 arrays.
I have 2 files from which I read the content:
file1: item_list.txt
string1 \n
string2 \n
string3 \n
...
file2: item+info.txt
string3 \t info1 \t info2 \t info3
string1 \t info7 \t info1 \t info4
string5 \t info2 \t info3
string2 \t info2 \t info4 \t info1
(values are separated by new lines and tabs only, I added one space between characters here just to increase readability).
I read from files using fgetcsv() function, and each row from file is stored as an array into a variable $data. I created a while loop with condition (!feof($fp)) to read through the file until the last row. But I can't quite properly nest the second loop.
What I want to do with this:
read the first string found in file1, go to file2 and try to find that string. If there's a match, get the info data for that string (all of the data, or just one, doesn't matter). If there's no match, return message "no match". In either case, once the second loop has done it's thing, I need to read the second string in file1, and do the search in file2 again. Repeat this as long as there is something to read from the file1.
here are two versions of my code, they don't work, and I can't figure out why.
//opening the files
$fp = fopen("$DOCUMENT_ROOT/test/item_list.txt", "r"); #raw item list
$pf = fopen("$DOCUMENT_ROOT/test/item+info.txt", "r"); #item+info list
//read from first file
$line=0;
while (!feof($fp)){
$line++;
$data1 = fgetcsv($fp, "1000", "\n");
$item1= $data1[0];
echo "line: $line. item_list: ".$item1; //just to see on screen what's happening
print_r($data1); //same here, just to see what's going on
echo"<br />";
//searching for string in file2
$row=0;
while (!feof($pf)){
$row++;
$data2 = fgetcsv($pf, "1000", "\t");
$item2= $data2[0];
echo "line: $row. item+info: ".$item2; //just checking things on screen
print_r($data2); //here too
echo "<br />";
//conditioning
//equal strings
if ($string1== $string2)
echo $data2[1]."<br />";
break;
}
}
fclose($fp);
fclose($pf);
this used to work as long as the items in item_list.txt and item+info.txt are oredered
exactly the same (string1\nstring2\string3 ->
string1\tinfo1\nstring2\tinfo2\nstring3\tinfo3 - but that's never going to happen in my
case, it's impossible to order the items like that)
I tried to do it with foreach() statement do itterate through arrays, but the result is something that I can't make any sense out of.
while (!feof($fp)){
$data1 = fgetcsv($fp);
foreach ($data1 as $token1) {
while (!feof($pf)) {
$data2 = fgetcsv($pf);
foreach ($data2 as $value) {
explode ("\t", $value);
if ($token1 == $value[0])
echo $value[1];
}
break;
}
}
}
This should do it:
$file1 = file($DOCUMENT_ROOT . '/test/item_list.txt');
$file2 = file($DOCUMENT_ROOT . '/test/item+info.txt');
foreach ($file1 as $line)
{
$line = rtrim($line); // just in case ...
if ($line === '') continue;
foreach($file2 as $infoline)
{
$infoline = explode("\t", rtrim($infoline);
if ($line === $infoline[0])
{
array_shift($infoline);
echo $line . '<br /><br />' . implode('<br />', $infoline);
// $results[$line] = $infoline; // uncomment this if you need the search results stored for later use
break;
}
}
}
Here's a rough shot at it:
$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';
# Init the Raw Array
$content2raw = array();
# Get the File Contents for File 2
$file2 = file_get_contents( $filename2 );
# Split it into an Array by Line Breaks
$content2raw = preg_split( "/\n/" , $file2 , -1 , PREG_SPLIT_NO_EMPTY );
# Unset the variable holding the file contents
unset( $file2 );
# Init the Fixed Array
$content2 = array();
# Loop through the Raw Array
foreach( $content2raw as $l ){
// Each Line of Filename2
# Split the Line on Tabs
$t = preg_split( "/\s*\t\s*/" , $l , -1 );
# Set the Fixed Array, using the first element from the line as the key
$content2[ $t[0] ] = $t;
}
# Unset the Raw Array
unset( $content2raw );
# Get the File Contents from File 1
$file1 = file_get_contents( $filename1 );
# Split it into an Array by Line Breaks
$contents1 = preg_split( "/\n/" , $file1 , -1 , PREG_SPLIT_NO_EMPTY );
# Unset the variable holding the file contents
unset( $file1 );
# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
# Check whether a matching element exists in the array from File 2
if( !array_key_exists( $k , $content2 ) ){
// No Match Found
echo 'No Match';
}else{
// Match Found
echo 'Match Found';
var_dump( $content2[$v] );
}
}
Amendment, as per comment/feedback from #Bluewind
$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';
# Open and Split the file into an Array by Line
$content2raw = file( $filename2 );
# Init the Fixed Array
$content2 = array();
# Loop through the Raw Array
foreach( $content2raw as $l ){
// Each Line of Filename2
# Split the Line on Tabs
$t = preg_split( "/\s*\t\s*/" , $l , -1 );
# Set the Fixed Array, using the first element from the line as the key
$content2[ $t[0] ] = $t;
}
# Unset the Raw Array
unset( $content2raw );
# Open and Split the file into an Array by Line
$contents1 = file( $filename1 );
# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
# Check whether a matching element exists in the array from File 2
if( !array_key_exists( $k , $content2 ) ){
// No Match Found
echo 'No Match';
}else{
// Match Found
echo 'Match Found';
var_dump( $content2[$v] );
}
}
This is actually much less code than you seem to think. First, you read an info file and build a hash table out of it:
foreach(file("info_list") as $line) {
$line = explode("\t", trim($line));
$info[$line[0]] = $line;
}
then you iterate through the items file and look if there are matching entries in the hash:
foreach(file("item_list") as $line) {
$item = trim($line);
if(isset($info[$item]))
// we have some info for this item
else
// we have no info for this item
}
that's basically all about this

Categories