I want to replace one line of a file with php, how can i do it?
This is the code where i print the line that I want to replace:
$file = fopen("file.dat", "a+");
$eqs = file_get_contents("file.dat");
$eqs = preg_split( "/\n/", $eqs );
foreach ($eqs as $valor) {
if(strpos($valor, $sn) !== false){
echo $valor; //this is the line to replace
} else{
echo "Not found";
}
}
Thanks in advance
As decezeā¦ mentioned, unless the line is of fixed length, the easiest way is to process the whole file and output it to a new file.
Create a variable $newdata to append the processed data.
If your strpos statement !== false then you can change that text with the $replace_text variable and append that instead.
Once the loop has finished save your output to a new file. (If PHP has the appropriate permissions)
$file = fopen("file.dat", "a+");
$eqs = file_get_contents("file.dat");
$eqs = preg_split( "/\n/", $eqs );
$newdata = "";
foreach ($eqs as $valor) {
if(strpos($valor, $sn) !== false){
echo $valor; //this is the line to replace
$replace_text = "test";
$newdata = $newdata.$replace_text."/\n/";
} else{
$newdata = $newdata.$valor."/\n/";
}
}
$myfile = fopen("newfile.dat", "w") or die("Unable to open file!");
fwrite($myfile, $newdata);
fclose($myfile);
I would suggest this solution because it saves resources by processing line by line.
$source = fopen('file.dat', "r");
$target = fopen('file.dat.tmp', "w");
while ($line = fgets($source)) {
if(strpos($line, $sn) === false){
fputs($target, $line);
}
}
fclose($source);
fclose($target);
unlink('file.dat');
rename('file.dat.tmp','file.dat');
Related
$my_content = "This is the first line\n
This is the second line\n
This is the third line\n";
$my_filename = "save.txt";
function file_writer(string $file_to_write, string $content_to_write){
$file = fopen($file_to_write, "w") or die("Unable to open file");
file_put_contents($file_to_write, $content_to_write);
fclose($file);
}
file_writer($my_filename, $my_content);
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
while(! feof($file))
{
$line = fgets($file);
echo $line;
}
}
**file_reader($my_filename, 3);**
Try this:
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$c = 0;
while(! feof($file) && $c != $num_lines)
{
$c = $c+1;
$line = fgets($file);
echo $line;
}
}
Your other problem is that you have newlines after newlines.
$my_content = "This is the first line\nThis is the second line\nThis is the third line\n";
function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$currLineNo = 1;
while(!feof($file) && (currLineNo < $num_lines))
{
$line = fgets($file);
echo $line;
$currLineNo += 1;
}
}
Havent tried the code myself. This is roughly way you can stop the loop at arbitrary line number.
Solved on 2 steps:
Get the lines: https://stackoverflow.com/a/51350572/8524395
Remove the lines after getting them: https://stackoverflow.com/a/51377052/8524395
I have a large file, I want to take 1000 lines from the end of this file, then remove them.
I am currently using this:
function deleteLineInFile($file,$string)
{
$i=0;
$array=array();
$read = fopen($file, "r") or die("can't open the file");
while(!feof($read)) {
$array[$i] = fgets($read);
++$i;
}
fclose($read);
$write = fopen($file, "w") or die("can't open the file");
foreach($array as $a) {
if(!strstr($a,$string)) fwrite($write,$a);
}
fclose($write);
}
$goods = '';
$file = file("../products/".$PidFileName);
for ($i = max(0, count($file)-1001); $i < count($file); $i++) {
$goods = $goods.$file[$i] . '<br />';
deleteLineInFile("../products/".$PidFileName, $file[$i]);
}
I want to save the lines which I got in $goods
However, it times out because of the file size.
If you want to get N lines from EOF, you can use SPLFileObject (added in PHP 5.1):
$num_to_cut = 1000; // must be an integer and not a string
$new_file = new SplFileObject("limited_test.txt", "w");
$old_file = new SplFileObject('test.txt');
// here we get count of lines: go to EOF and get line number
$old_file->seek($old_file->getSize());
$linesTotal = $old_file->key()+1;
// and write data to new file
foreach( new LimitIterator($old_file, $linesTotal-$num_to_cut) as $line) {
$new_file->fwrite($line);
}
To remove the lines after getting them from a LARGE file:
The best way to do that is to use sed | But if you don't have access to use the exec() function then this is a function that you can use.
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
Source of the function: https://stackoverflow.com/a/2159135/8524395
To remove the line use it like that:
replace_file('myfile.txt', 'RemoveThisPlease', '');
If you used MrSmile's answer to get the lines, then replace "RemoveThisPlease" with $line
I am trying to add a string to the end of eachline. So far this works. However I dont want the string to be added to the end of the first line. How can I do this?
So far i have got:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
I have also tried to loop it by doing this:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
if ($x > 0) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
$x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
So the end result would look like:
firstonestring
secondonestring
thirdonestring
and so on.
I hope you can help me!
Ben :)
Just add a counter to your loop:
$counter = 0;
while(!feof($baseFile)) {
$line = fgets($baseFile)
if($counter++ > 0){
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}else{
$newFile.= $line . "\n";
}
}
Also, you seem to be writting the new file, only to reopen it and append more data. There is no need to do that, just append to the contents before you write it the 1st time:
fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);
//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);
Alternativly, you can just read in the whole file, split into lines, and rejoin:
$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!
By using a flag
$first = TRUE;//set true first time
while (!feof($baseFile)) {
$line = fgets($baseFile);
if (!$first) {// only enter for false
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}
$first = FALSE;// set false except first
}
I have some PHP function that requires the line number of a CSV file used as database. Once it has line, it navigates to the specific value that needs to be changed, changes it and rewrites the whole files. Here is my code:
<?php
function update($file, $id, $field, $value)
{
//$id is the line number
$contents = explode("\n", file_get_contents($file));
$fh = fopen($file, "w");
$lines = array();
foreach($contents as $line)
{
if($line == "")
continue;
$fields = explode("|", $line);
if($fields[0] == $id)
{
$line = null;
for($i = 0; $i<count($fields); $i++)
{
if($i == $field)
$fields[$i] = $value;
if($i != count($fields)-1)
$line .= $fields[$i]."|";
else
$line .= $fields[$i];
}
}
$line .= "\n";
fwrite($fh, $line);
}
fclose($fh);
$contents = null;
return true;
}
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
echo "updated!";
?>
I am unable to find the problem because whenever I run the code, it outputs "updated!" just as it should but when check the file, I find it has not been updated. I do not know why, but it always remains the same! Thanks.
Check that fwrite() is not failing.
Do something like this:
...
$writeSuccess = (fwrite($fh, $line) !== false);
}
fclose($fh);
$contents = null;
return $writeSuccess;
}
...
If it is failing, check that your filesystem permissions are correctly set. The Apache user needs to have write access to whatever file/folder you are writing the file to.
I found out what the problem was.
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
The line number pointed to the previous line, which made it impossible to update the first line of the file. So all I had to do was
$line ++;
I have a text file here which I need to be able to convert into rows to extract the second, third, fourth, and fifth values from.
The first 7 values of each row are tab delimited, then there is a newline, then the final three values are tab delimited.
I removed the interrupting newlines so that each row is fully tab delimited.
<?php
$file="140724.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$remove = "\n";
split = explode($remove, $fread);
foreach ($split as $string)
{
echo "$string<br><br>";
}
?>
Which produces this.
I'm not sure where to progress from this point. I'm teaching myself PHP and am still quite new to it, so I don't even know if where I've started from is a good place. My instinct is to write the previous output to a new textfile, then create another block of code similar to the first but exploding based on tabs, this time.
Help?
You can process this file in one go like this:
<?php
$file="140724.txt";
$fopen = fopen($file, 'r');
$fread = fread($fopen,filesize($file));
fclose($fopen);
$remove = "\n";
$split = explode($remove, $fread);
$array[] = null;
$tab = "\t";
foreach ($split as $string)
{
$row = explode($tab, $string);
array_push($array,$row);
}
echo "<pre>";
print_r($array);
echo "</pre>";
?>
The result will be a jagged array:
You will need to clean up the 1st and the last element.
That is structured data, delimited by tabs. You can use fgetcsv() to read that data into an array. For an example see the PHP documentation.
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
$text[] = fgets($myfile);
}
fclose($myfile);
print_r($text);
?>
There is another answer here which converts file/raw strings into an associative array. It is really very handy in such cases.
function tab_to_array($src='', $delimiter=',', $is_file = true)
{
if($is_file && (!file_exists($src) || !is_readable($src)))
return FALSE;
$header = NULL;
$data = array();
if($is_file){
if (($handle = fopen($src, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
}
else{
$strArr = explode("\n",$src);
foreach($strArr as $dataRow){
if($row = explode($delimiter,$dataRow))
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
}
}
return $data;
}
/**
* Example for file
*/
print_r(tab_to_array('example.csv'));
/**
* Example for raw string
*/
$str = "name number
Lorem 11
ipsum 22";
print_r(tab_to_array($str, "\t", false));