简体   繁体   中英

Modify content of file in 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 (ie, 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

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM