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

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);
}

Related

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);
}

Get value from file - php

Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];

Reformatting The Content Of A File

I have a file called "data.txt". In this file, there are 30 lines with strings who all have the same length. It looks like this:
2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
... and so on.
What I want to do now is reformatting these lines. I want 5 strings on one line, seperated with a ";". After that, I want a new line and the next 5. In the end, it should look like this:
2QA4ZRDUT;IDVLTLZSC;4GYC3HCMV;1W6409JD5;70P7U66TE;
NGN1TGF6G;JWVI7LSIZ;U99TMVXXK;KLBDMRPQV;MEFKLUO3;
... and so on, until the whole content of the file is reformatted like this.
The last hours I've been trying to accomplish this by using for, foreach and while loops but I only manage to get one line. I hope somebody can help me since I'm not that experienced with PHP.
This is the content of "data.txt":
2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
OG2JBBZF6
5391PHOVW
ZAJ3OZ4H2
GMOB9E9X7
Q8U4C8ZK1
0WDZLRWWJ
N487W3S24
PKXQFFEK3
NSMKC29IB
HOLI1T2ZB
DVPIVLLLS
FH7RSZWTM
9VSUWPZEX
NM6ZWV19I
NGN1TGF6G
JWVI7LSIZ
U99TMVXXK
KLBDMRPQV
MEFKLUO3L
LICFIK24W
ELGPLCK51
QQS4SOJV1
KJ2UVTU1B
FLQ6T7LG6
QJZLAPYN1
something like that:
<?php
$oldf=fopen('data.txt','r');
$newf=fopen('data_new.txt','w');
$i=0;
while(!feof($oldf))
{
$i++;
$line=fgets($oldf);
fwrite($newf,$line.';');
if($i%5==0)
fwrite($newf,"\n");
}
fclose($oldf);
fclose($newf);
Try this:
<?php
$file_name = "test.txt"; // Change file name as needed
$file_data = file_get_contents($file_name);
$file_data_array = explode('\n', $file_data);
$i = 0;
$new_file_data = "";
foreach ($file_data_array as $piece)
{
$new_file_data .= $piece . ';';
$i++;
if ($i % 5 == 0) // Change number of pieces you want on a line as needed
{
$new_file_data .= '\n';
}
}
file_put_contents($file_name, $new_file_data);
?>
This should do it:
$str = '2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
OG2JBBZF6
5391PHOVW
ZAJ3OZ4H2
GMOB9E9X7
Q8U4C8ZK1
0WDZLRWWJ
N487W3S24
PKXQFFEK3
NSMKC29IB
HOLI1T2ZB
DVPIVLLLS
FH7RSZWTM
9VSUWPZEX
NM6ZWV19I
NGN1TGF6G
JWVI7LSIZ
U99TMVXXK
KLBDMRPQV
MEFKLUO3L
LICFIK24W
ELGPLCK51
QQS4SOJV1
KJ2UVTU1B
FLQ6T7LG6
QJZLAPYN1';
$arr = explode(PHP_EOL, $str);
$c = 1;
$str3 = '';
foreach ($arr as $item) {
$str3.= $item.';';
if ($c % 5 == 0) {
$str3.= PHP_EOL;
}
++$c;
}
echo "<p>$str3</p>";
Be aware that you won't see the line breaks in the browser, but they will be apparent when you 'view source'.
Edit: I'm using PHP_EOL here instead of "\n" as the other answers have suggested. This ensures that the script will work correctly on any platform (Win, MacOS & *nix) as long as the PHP setting auto_detect_line_endings is set to true

PHP easy-to-solve

<?
[...]
$line = fgets($file);
while(!feof($file)){
if(($line)!==('da7or')){
{
echo fgets($file)."<br />";
}
}}
[...]
?>
file is something like:
nick1
da7or
nick3
nick4
nick5
I don't want "da7or" to be displayed but it always removes nick from the 1st line of the file.
since you are calling twice fgets try somthing like:
[..]
while(!feof($file))
{
$line = trim(fgets($file));
if(($line)!==('da7or'))
{
echo $line ."<br />";
}
}
[..]
notice there's no fgets before the while
fgets() also returns linebreak characters. You'll have to do
if (trim($line) !== 'da7or')
to strip off those characters. Note that if any of your lines also START with whitespace characters, trim will also remove those as well.
Beyond that, your logic is flawed.
You fetch a line, compare is against da7or, then simply directly output every line AFTER this. Your loop should be:
while ($line = fgets($file)) {
if (trim($line) !== 'da7or') {
echo $line
}
}
Using a loop to read in a file line-wise is kinda stupid.
Because there is a function for that: file()
$names = file("names.txt", FILE_IGNORE_NEW_LINES);
$names = array_diff($names, array("da7or"));
And the simple array_diff removes the unwanted element from the list. Then just print out the rest.
You never update $line after the first time.
<?php
while (!feof($file) && $line = fgets($file))
{
if (trim($line) != 'da7or')
echo $line;
}
You have to choose, if you read the file line into $line you can't echo the fgets, you need to echo $line (and reload the $line variables with a fget)

Categories