简体   繁体   中英

Write data on specific line into the file with PHP

Is there way to append data to file on specific line or something similar like that?

I have an "handmade" array in my file, and I need to keep my beginning and end of the array.

I would like to have something like this:

$array = [
    *create new line and write data here*,
*previous data*,
*previous data*,
*previous data*,
];

EDIT: I currently only know how to append data at the end of the file, and I haven't found proper solution. If I append my data with just file_put_contents(); , it won't be in the array:

$array = [
    *previous data*,
    *previous data*,
    *previous data*,
    ];
*create new line and write data here*,

EDIT: I got my answer. There is no efficient way to do this.

You can't add a line in a middle of a file. You need to rewrite the file with something like this (not memory expensive) :

// Read your old file
$read = fopen('myfile', 'r');
// Create a new file
$write = fopen('myfile.tmp', 'w');

while (!feof($read)) {
  $line = fgets($read);
  if (stristr($line, '$arr = [')) { // For your case
    $line .= "YOUR NEW LINE\n";
  }
  fputs($write, $line);
}

fclose($read);
fclose($write);
// Rename the new file
rename('myfile.tmp', 'myfile');

To add elements at the beginning of an array use array_unshift:

$a=array ("content of a line", "another line");
array_unshift($a, "content to be added");

print_r($a); //print out to check

'array_push' does the same but add element(s) at the end of the array

If writing to a file, there are not many (any, in my personal experience!) options for efficient prepending or mid-file inserts. Almost all of the working world relies on appending to files. You can do it, but only through basically rewriting the entire file. In essence, you have to "move all the other lines down", and that takes work.

If this is something you need done efficiently, consider a more appropriate data structure. Perhaps multiple arrays (eg, perhaps in reverse order), multiple files, a sorting key for after load sorting, etc. But you are not likely to get around the issue of slow performance when prepending or inserting to on-disk files. (And if you do, likely involving some kernel editing, then consider making some money or helping the FOSS world out!)

If you are doing this in memory, then the data structures and access patterns are much more robust, and so you can do operations like array_unshift :

$arr = [
  "line 1",
  "line 2",
  "line ..."
];

array_unshift($arr, "line 0");
# $arr is now: [
#  "line 0",
#  "line 1",
#  "line 2",
#  "line ..."
#];

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