Modify content of file in php - php

This file stores the number of item ordered to date. Therefore, I will need to read from the file for current number ordered and add it to the current quantity ordered and write it back.
I am new to PHP, so I am not sure what is the best approach here.
The format of the file is as follows:
$filename = "ordersToDate.txt";
if (!file_exists($filename))
{
$file = fopen($filename, "w");
$toWrite = "Total quantity ordered to date
\r\nTotal number of apples: ".$appleQty.
"\r\nTotal number of oranges: ".$orangeQty.
"\r\nTotal number of bananas: ".$bananaQty;
fwrite($file, $toWrite);
fclose($file);
}
else
{
// read individual item QTY ordered to date, add it with current ordered QTY and write back
}
If the file already exists, I need to read the QTY from it and update it. Is there a quick and easy way to get it (i.e., current QTY to date), provided that I know the string before it?

When you open a file like that you can specify "or die" like this:
$filename = fopen("ordersToDate.txt", "w") or die ("Can't open file.");
Then you can write to the file like you're doing and then close it. If the file exists already it will just open the existing one. If it doesn't exist PHP will create the file.

<?php
// can add another one for 'bananas: ' etc.
$re = "/(?!apples: )(\\d)/"; // for apples
// $str = file_get_contents($filename);
$str = "Total quantity ordered to date\r\nTotal number of apples: 3\r\nTotal number of oranges: 4\r\nTotal number of bananas: 3";
$subst = "5"; // $subst = $new_number;
// replace the number after 'apples: ' with whatever you want
$result = preg_replace($re, $subst, $str, 1);
echo var_dump($result);
// file contents, with apple number replaced with 5 (from 3) can now be written to file
?>

Related

Removing A Specific Line From A File

I have a text file like this:
1
2
3
4
5
6
7
8
9
10
And I want to remove specific lines which numbers are in an array like this:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
//wanna remove these lines
So I tried this code but It didn't work and It just doubles the text and ruins everything:
<?php
$myfile='txt.txt';
$remove=array(1,3,5,7,10);
$lines=file($myfile);
$countline=sizeof($lines);
$data=file_get_contents($myfile);
for ($i=0; $i < $countline+1; $i++) {
if (in_array($i, $remove)) {
$editeddata=str_replace($lines[$i], "", $data);
$removeline = file_put_contents($myfile, $editeddata.PHP_EOL , FILE_APPEND | LOCK_EX);
}
}
?>
I couldn't use ((for)) properly and I think it will just ruin the text because it deletes lines one after another have been deleted and it changes the order so I should have a code to remove them all at once.
And please don't give a code to just replace numbers because the main text file is not only numbers and contains word,etc...
Thanks A lot!
You're reading the file twice (with file and file_get_contents), which I think is confusing the later code. You have everything you need with the first call - an array of all the lines in the file. You're also using str_replace to remove the content, which seems a bit dangerous if any of the content is repeated.
I'd refactor this to simply filter the array of lines based on their line-number, then write it back to the file in a single operation:
$myfile = 'txt.txt';
$remove = [1, 3, 5, 7, 10];
// Read file into memory
$lines = file($myfile);
// Filter lines based on line number (+1 because the array is zero-indexed)
$lines = array_filter($lines, function($lineNumber) use ($remove) {
return !in_array($lineNumber + 1, $remove);
}, ARRAY_FILTER_USE_KEY);
// Re-assemble the output (the lines already have a line-break at the end)
$output = implode('', $lines);
// Write back to file
file_put_contents($myfile, $output);
If the file fits in memory then you can do the simple:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
file_put_contents($myfile, implode(PHP_EOL,array_diff($file($myfile,FILE_IGNORE_NEW_LINES), $remove)));
Note: Because it's a bit ambiguous whether $remove has the content or the lines you want to remove, the above code removes the content . If you want to remove lines change array_diff($file($myfile,FILE_IGNORE_NEW_LINES), $remove) to array_diff_keys($file($myfile,FILE_IGNORE_NEW_LINES), array_flip($remove))
If your file is large then you need to resort to some sort of streaming. I suggest against reading and writing to the same file and doing something like:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
$h = fopen($myfile,"r");
$tmp = fopen($myfile.".tmp", "w");
while (($line = fgets($h)) !== false) {
if (!in_array(rtrim($line, PHP_EOL), $remove)) {
fwrite($tmp, $line);
}
}
fclose($h);
fclose($tmp);
unlink($myfile);
rename($myfile.".tmp", $myfile);

Php loop and count through txt file

I got a bit of a complex problem. At work we have to count our inventory every month. This is done with a scanner. At each location there can be up to 100 different items. Every item, even the same kind have to be scanned. When each location has been scanned, we print out the list of scanned items. The problem is that each scan has its own line in the txt file (it done not add/subtract multiple counts of the same item)
As the vendor of our system is notoriously slow implementing new functions I thought about a php script that does the following:
1: read every line from the txt file
2: add/substract the count of the same item
3: print out a list with the item number and count.
The txt file is as following:
01234+000001N
Where the first 5 digits is the item number. As it is possible to add and substract the next symbol is + or - then the next 5 digits is the count and the N is the "eol"
So somehow I have to put it all in some sort of array and the sort it by item number. And the add/substract and then finally print out the final list
Assuming you've loaded the file into a string, line by line, and is split by a new line, you can do the following; (read code comments)
$strTxtFile = <<<TXT
01234+000001N
01234+000001N
09876+000002N
01234+000001N
01234+000001N
09876+000002N
01234-000001N
09876+000002N
TXT;
/**
* 01234 should have 3 stock
* 09876 should have 6 stock
*/
$arrProducts = array();
$arrFileLines = explode(PHP_EOL, $strTxtFile);
foreach($arrFileLines as $strFileLine) {
//Split the lines by the action (+/-)
$arrStockAction = preg_split("/(\+|\-)/", $strFileLine, NULL, PREG_SPLIT_DELIM_CAPTURE);
$strProductCode = $arrStockAction[0]; //The first part is the product code
$strAction = $arrStockAction[1]; //The action (+/-) to the stock
$intStockAmount = (int) $arrStockAction[2]; //Cast it to an int to get the number
//Check if the product exists in our array, if not, create it with 0 stock
if( array_key_exists($strProductCode, $arrProducts) === FALSE ) {
$arrProducts[$strProductCode] = 0;
}
if($strAction === "+") {
//Add stock
$arrProducts[$strProductCode] += $intStockAmount;
} else {
//Minus stock
$arrProducts[$strProductCode] -= $intStockAmount;
}
}
print_r($arrProducts);
https://repl.it/ECrW
Similar to the other answer, maybe a little simpler:
foreach(file('/path/to/file.txt') as $line) {
$item = substr($line, 0, 5);
$sign = substr($line, 5, 1);
$qty = substr($line, 6, 6);
if(!isset($result[$item])) {
$result[$item] = $qty;
} else {
$result[$item] += $sign.$qty;
}
}
Or replace the substr() lines with:
preg_match('/(\d{5})(.)(\d{6})/', $line, $matches);
And use $matches[1], $matches[2] and $matches[3].
I just found out I had misread the txt file. The lines is as follow:
01234000001 N
And
01234000001-N
The blank space between the last number and the N represent addition and - substract

Writing value to file

Struggling!
The following code is supposed to take the value from a form, add that value to a value which it reads from data.php then rewrite the new value to data.php
<?php
//get form value
$add_value = $_GET["txt_InterimDonationSubtotal"]; //Will always be a number (10.00, for example)
echo $add_value;
// get contents of a file into a string
$filename = "../assets/files/donation_total/data.php";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
//Say what you got!
echo $contents;
//Get the numbers outta there :) (Will be some kind of number '100.00' for example)
$value = substr($contents, 13);
$value_cleaned = substr($value, 0, -4);
//Add the two numbers together
$new_total = $value_cleaned + $add_value;
//Rewrite the values back to the file
$new_data_content = "<?php $$data=$new_total;?>";
file_put_contents('../assets/files/donation_total/data.php', $new_data_content);
?>
The output does not echo anything, as it should (just for now, I'll remove it when i know it's working), it does write something back to data.php, but not what it should. The following is what I get in data.php when I open it in Sublime:
<?php $=0;?>
As you can see, the name of the variable 'data' is not being saved in the file, and it is not adding the values together! Why?!
Desired output is along the lines of:
<?php $data='125.85';?>
Thanks to the help of people answering I've got this far:
<?php
//get form value
$add_value = $_GET["txt_InterimDonationSubtotal"]; //Will always be a number (10.00, for example)
echo $add_value;
// get contents of a file into a string
$contents = file_get_contents('../assets/files/donation_total/data.php');
//Say what you got!
echo "contents:".$contents;
//Get the numbers outta there :) (Will be some kind of number '100.00' for example)
$value = substr($contents, 13);
$value_cleaned = substr($value, 0, -4);
//Add the two numbers together
$new_total = $value_cleaned + $add_value;
echo "newtotal:".$new_total;
//Rewrite the values back to the file
$new_data_content = "<?php $data='".$new_total."';?>";
file_put_contents('../assets/files/donation_total/data.php', $new_data_content);
?>
This now naming the variable just fine, but the contents are not being read and echoed (why?!) and the values are not being added together, because it's not doing a great job of getting the file contents to being with I'm guessing.
This is because strings with double quotes have variables within them magically interpreted. When PHP sees the string "<?php $$data=$new_total;?>" it says where are the variables $data and $new_total then evaluates those variables within the string. $new_total is a defined variable and its value is written to the string but $data is not so it's value is not.
You could however write your string where it is not evaluated at all using single quotes like this '<?php $$data=$new_total;?>'. However then all the text would be written literally to your file.
What I think you want is to concat the string with the value. '<?php $data="' . $new_total . '";?>'
Did you try serialization?
<?php
$add_value = $_POST["txt_InterimDonationSubtotal"];
$contents = file_get_contents("../assets/files/donation_total/data.txt");
if($contents) {
$contents = unserialize($contents);
} else {
$contents = 0;
}
$contents += $add_value;
file_put_contents('../assets/files/donation_total/data.txt', serialize($contents));
?>

How to split content into equal parts then write to file in PHP

I have been reading/testing examples since last night, but the cows never came home.
I have a file with (for example) approx. 1000 characters in one line and want to split it into 10 equal parts then write back to the file.
Goal:
1. Open the file in question and read its content
2. Count up to 100 characters for example, then put a line break
3. Count 100 again and another line break, and so on till it's done.
4. Write/overwrite the file with the new split content
For example:
I want to turn this => KNMT2zSOMs4j4vXsBlb7uCjrGxgXpr
Into this:
KNMT2zSOMs
4j4vXsBlb7
uCjrGxgXpr
This is what I have so far:
<?php
$MyString = fopen('file.txt', "r");
$MyNewString;
$n = 100; // How many you want before seperation
$MyNewString = substr($MyString,0,$n);
$i = $n;
while ($i < strlen($MyString)) {
$MyNewString .= "\n"; // Seperator Character
$MyNewString .= substr($MyString,$i,$n);
$i = $i + $n;
}
file_put_contents($MyString, $MyNewString);
fclose($MyString);
?>
But that is not working quite the way I anticipated.
I realize that there are other similiar questions like mine, but they were not showing how to read a file, then write back to it.
<?php
$str = "aonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaon";
$pieces = 10;
$ch = chunk_split($str, $pieces);
$piece = explode("\n", $ch);
foreach($piece as $line) {
// write to file
}
?>
http://php.net/manual/en/function.chunk-split.php
Hold on here. You're not giving a file name/path to file_put_contents();, you're giving a file handle.
Try this:
file_put_contents("newFileWithText.txt", $MyNewString);
You see, when doing $var=fopen();, you're giving $var a value of a handle, which is not meant to be used with file_put_contents(); as it doesnt ask for a handle, but a filename instead. So, it should be: file_put_contents("myfilenamehere.txt", "the data i want in my file here...");
Simple.
Take a look at the documentation for str_split. It will take a string and split it into chunks based on length, storing each chunk at a separate index in an array that it returns. You can then iterate over the array adding a line break after each index.

array_unique not working with filename strings imported from text file

THE PROCESS:
User checks checkboxes to share files with customer accounts
Checkbox values are compared against an array stored in a txt file from the customers folder
The arrays are compared by being merged into one array using array_merge()
The duplicates are eliminated using array_unique()
New array written to txt file
THE PROBLEM:
If my text file already contains the following data: (numbers representing text file lines)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
M HTH A277 Frame On STD Specs 02-01-12.pdf
M HTH Option Can Price List 02-02-2012.xls
I then try to share more files including those that are already shared. My new text file looks like this: (numbers representing text file lines)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
(blank)
M HTH A277 Frame On STD Specs 02-01-12.pdf
(blank)
M HTH Option Can Price List 02-02-2012.xls
(blank)
(blank)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
M HTH A277 Frame On STD Specs 02-01-12.pdf
M HTH Option Can Price List 02-02-2012.xls
Valley Creek Estates - 2010.pdf
The values above are the exact values I'm dealing with. I've tried to be as thorough as possible with this explanation which could make things confusing. If anyone can provide me with any suggestions they would be greatly appreciated. Thanks in advance. This is what I've got for code so far:
THE CODE:
$arr = $_POST['checked'];
$cust = $_POST['custname'];
if ($cust != ""){
$myFile = "CONTA.txt";
//If file exists get previous array from file
if (file_exists("customer/" . $cust . "/" . $myFile)) {
$fh = fopen("customer/" . $cust . "/" . $myFile, 'r') or die("");
while (!feof($fh) ) {
$compare[] = fgets($fh);
}
fclose($fh);
//Combine checkbox array with previous array & eliminate duplicates
$combined = array_unique(array_merge($compare,$arr));
}
else
{
//Since no previous file or array existed. Just use current checkbox array.
$combined = $arr;
}
//Input array into file
$fh = fopen("customer/" . $cust . "/" . $myFile, 'w') or die("can't open file");
foreach ($combined as $value) {
fwrite($fh, $value . "\n");
}
echo "<span class='message'>Items shared successfully!</span>";
fclose($fh);
}
}
To me it looks like the problem is "\n" character. Each line has a new line on the end and when you compare one line that has the newline character and the same line that doesn't they aren't the same. I would confirm this by echoing each line from the fgets. If they are line broken, then you know you are getting the new line character.
EDIT:
I would try putting
trim(fgets($fh))
by default it should strip the newline character
trim specs

Categories