PHP insert in file - php

I have to insert text to a file at a specific position without reading/writing the entire file. Is that possible using just php?
mytext.txt content is 123456789
<?php
$message='new';
$file='mytext.txt';
$fh = fopen($file, 'rw+');
fseek($fh, 3);
fwrite($fh, $message);
fclose($fh);
?>
This code overwrites at the specified location.
I'm looking for '0123new456789' not '123new789'

I don't think what you want to do is possible without reading the file first. This should help, though:
// Get file contents
$contents = file_get_contents($file);
// Split your strings
$beginning = substr($contents, 0, 4);
$ending = substr($contents, 4, 6);
// Re-write contents
$contents = $beginning . $message . $end;
// Write file contents
file_put_contents($file, $contents);
Thanks,
Andrew

You have no choice.
fopen() allways put the pointer at the beginning or end of file. In any case you must to pass trough the file untill you find what you are looking for. There you can close.
See the document about it http://php.net/manual/en/function.fopen.php
By the way, fseek($fh, 3) is not mean to find 3. Is is retrieve something in the 3 bytes length. See http://php.net/manual/en/function.fseek.php

Related

fwrite overwrite without closing the connection

How to overwrite a text using fopen
$data = 'HHHHHHHHHHHHHHH';
$data2 = 'JJJJJJJJJJJJJJ';
$F = fopen('tbbbb.txt','w');
fwrite($F,$data);
fwrite($F,$data2);
fclose($F);
I want output should be
"JJJJJJJJJJJJJJ"
in the file
You can use the fseek() function:
fwrite($F,$data);
fseek($F, 0);
fwrite($F,$data2);
Use rewind to return to the beginning of the file.
fwrite($F,$data);
rewind($F);
fwrite($F,$data2);
The resulting file contents will be:
JJJJJJJJJJJJJJH
because overwriting the beginning of the file doesn't replace what comes after it. You can call:
ftruncate($F, count($data2));
to set the file length.
fwrite will always write where the cursor position is and navigate the cursor to next line. So when you write first string, it will write to first line and navigate the cursor to next line. SO current cursor position is on second line. So if you want to overwrite a particular line you will have to seek to that line.
fseek($F, <byte_position>);
fwrite($F, <string>);
Use file_put_contents()
file_put_contents('file.txt', $data);
echo file_get_contents('file.txt'); // HHHHHHHHHHHHHHH
file_put_contents('file.txt', $data2);
echo file_get_contents('file.txt'); // JJJJJJJJJJJJJJ

how to replace some part of text from the text file in php

I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).

parsing a file from end

I have a text file that has information like this
##john##eva##shawn##roger##henry##david
I want to get the very last name at the end and ingnore rest.
How'd I do that
THanks
Big file solution:
$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");
$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
$seek_position = $seek_position - 1024;
if(abs($seek_position) > $file_size)
break;
fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
Small file solution:
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);
Use fseek to quickly jump to the end of the file.
$handle = fopen("myfile.txt", "r");
fseek($handle, -20, SEEK_END);
$bytes = fread($handle, 20);
Will read the last 20 bytes of the file (and skip the rest).
Unless you know how long the last name is going to be or at least the max length of names you can't really skip just to end of a file and pull out the name.
What you need to do is read the file into a buffer and parse it either using something like explode() and '##' and getting the last element of the returned array or using strpos() to find the last occureance of '##'and reading on from there.
Here is an example with explode.
$sFileName = "file.txt";
$sContents = file_get_contents($sFileName);
$aNames = explode("##", $sContents);
$sLastName = $aNames[count($aNames)-1];
After loading the file into a variable, you can find the last ocurrence of "##" using strpos() and then read from there on using substr().
You can explode the whole string to an array and then use the php's end() function, like this:
// define our string
$string = "##john##eva##shawn##roger##henry##david";
// use the explode function to create an array using the delimiter ##
$array = explode("##", "##john##eva##shawn##roger##henry##david");
// print last object of the array using the php's end function
print end($array);

textfile to an array...any ideas?

I am needing to turn a textfile into an array...I am not sure how to go about this because the other features ive seen for php take an entire file and put it into an array but not quite how I want it to be so I am looking for advice here..
The following is written in a textfile:
"jim kroi,richard wuu,yan kebler,justin persaud"
How can I use php to make an array where automatically a loop puts each name as an item of the array until all the names run out?
so the end result of what I am trying to do is:
$array= array("jim kroi","richard wuu","Yan kebler","justin persaud");
So a loop of some sort would basically search upto each comma and extract the name before it until all of the names run out....
There are some php substr and such functions but I cant quite think of how to do this..
Yes, I do have code, here it is:
<?php
error_reporting(-1);
$fp = fopen('numbers.csv', 'w');
fputcsv($fp, $_POST['names']);
fputcsv($fp, $_POST['numbers']);
fclose($fp);
?>
i put them all in a csv but now how can I make 2 arrays, one with name the other with numbers? http://imageshack.us/photo/my-images/215/csv.png/
using implode I get the error:
Warning: implode() [function.implode]: Bad arguments. in C:\Program Files\xampp\htdocs\xampp\something.php on line 14
<?php
error_reporting(-1);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
fclose($fh);
?>
Try to use fgetcsv with a custom separator.
Something like:
$names = array_map('trim', explode(',', file_get_contents('%yourFileHere')));
Use the explode() function.
$string = "jim kroi,richard wuu,yan kebler,justin persaud";
$arrNames = explode(',', $string);
var_dump($arrNames);
see explode, read the file with file_get_contents
You can try explode;
$names = explode(',', $line);
http://php.net/manual/en/function.explode.php
it's simple
<?PHP
$myFile = "testFile.txt"; // file path and name
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
?>

How to transfer set of text from file to file using two identifiers using PHP?

This code below can migrate the two variables from one file into the other.
<?php
$file = 'somefile.txt';
// Open the file to get existing content
$current = fopen($file,'a');
// Append a new person to the file
$firstname .= "aiden\n";
$secondname .= "dawn\n";
$currentContent = file_get_contents($file);
// Write the contents back to the file
$fileFound = 'people.txt';
$newFile = fopen($fileFound,'a');
//if $current and $nextcurrent is found in the somefile.txt it will transfer the content to people.txt
if (strpos($currentContent,$firstname) !== 0)
{
if (strpos($currentContent,$secondname) !== 0)
{
fwrite($newFile, $currentContent."\n");
} // endif
}// endif
?>
The next problem is, how am i able to migrate the texts from identifier one up to identifiers two?
I guess I'll have to use substr or a strrpos string here.
Help Please :)
I'm having a hard time understanding the problem but looks like you're trying to include anything between 'aiden' and 'dawn' from a file and write the result into a new file.
Give a shot for this one
$firstIdentifier = 'aiden';
$secondIdentifier = 'dawn';
$currentContent = str_replace("\n", "", file_get_contents('sourcefile.txt'));
$pattern = '/('.$firstIdentifier.')(.+?)('.$secondIdentifier.')/';
//get all text between the two identifiers, and include the identifiers in the match result
preg_match_all($pattern, $currentContent , $matches);
//stick them together with space delimiter
$contentOfNewFile = implode(" ",$matches[0]);
//save to a new file
$newFile = fopen('destinationFile.txt','a');
fwrite($newFile, $contentOfNewFile);
You don't need fopen when you are using file_get_contents
Instead of using a delimiter I'd suggest you just serialize your variables
In file 1:
file_put_contents('somefile.txt',serialize(array($firstname,$lastname)));
In file 2:
list($firstname,$lastname) = unserialize(file_get_contents('somefile.txt'))

Categories