Forum Moderators: coopster
Also, is it possible when creating a file using fopen() to include a variable in the name, like $variable".html" or something?
>> if there's an easier way to change the position I write to
I am guessing you are using something along the lines of fseek then. I don't use flatfile db's very often and usually they are small or have few columns. I load them into arrays sometimes or read through line by line and do things using line/record numbers.
>>is it possible when creating a file using fopen() to include a variable in the name, like $variable".html"
most definitely, I often construct the filename and pass the whole thing to fopen just in case I mess something up it is easier to debug
$filename = $variable . ".html";
$fp = fopen($filename,'r');
What you could do is read the file into a string, split it at the keyword, append the new string you want in the middle, and then rewrite the whole deal to the file.
That's the only way I can think of doing it. Mostly because just "writing at some point in the middle of the file" would end up overwriting the rest of the file.
//explode the string at your keyword
//returns an array
$split_at_keyword = explode('your_keyword', $file_as_a_string);
// $split_at_keyword is now an array
// if 'your_keyword' only occurs once, there will
// be two array elements
// otherwise, there may be alot of elements
// you'll have to taylor this to your needs
// get the first part of the file
$new_string = $split_at_keyword[0];
// add in your new stuff
$new_string .= "What you want to add";
// tack on the rest of the file
// implode collapses the array again back into a string
$new_string .= implode('',$split_at_keyword[1]);
// write your new string to a file
$fp = fopen($file, 'w+b');
fwrite($fp, $new_string);
fclose($fp);
Hope that helps :)
This isn't how I would do this.
If you ABSOLUTELY had to be able to rewrite a file from central section, I would probably key each line or section so I'd just know exactly where to jump to, rather than using the ambiguous 'split at a keyword' approach.
It's ambiguous because the keyword may exist in multiple places so you don't really know where to add in your new stuff.
Say your flat file was a list of news stories; I would separate them by something like
<<---1--->>
story
<<---2--->>
story2
etc...
Then when you printed them out you'd have a nicely organized array with the new stories in it. And appending new data in it is as simple as splitting at
<<---5--->> or something.