I am trying to read a formatted file
name (read this into variable)
10 10 (read into separate variables)
the rest into array
line
line
line
line
to clarify this is for an upload script which i already finished when a user uploads a file formatted like that it reads it in the way described above
$fname = 'test.txt';
$lines = file("$fname", "r");
while($lines as $currenline){
I am trying to put the name, width, height into variables
then the rest into the array
}
will this help
Not 100% sure what you're asking for but maybe this can get you started:
$fname = 'test.txt';
$lines = file("$fname", "r");
foreach($lines as $line) {
$parts = explode(' ', $line);
$name = $parts[0];
$width = $parts[1];
$height = $parts[2];
// Do whatever you want with the line data here
}
It assumes all input lines are well formatted of course.
$fh = fopen( $fname, 'r' );
$name = fgets( $fh );
$dimensions = split( ' ', fgets($fh) );
$length = $dimensions[0];
$width = $dimensions[1];
$lines = array();
while ( $line = fgets( $fh ) $lines[] = $line;
I never tested this, but it should work if your files are constant. The while loop maybe off, and need some re-working if it doesn't work, keeping in mind that fgets returns false if an error occurs or is unable to read the file.
$lines already contains almost what you need, just pull out the relevant pieces.
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = $lines[0];
list($height, $width) = explode(' ', $lines[1]);
$lines = array_slice($lines, 2);
Note this doesn't have any error checking, so you might want to add some.
As suggested in the comments you can also do this using array_shift:
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = array_shift($lines);
list($height, $width) = explode(' ', array_shift($lines));
// $lines now contains only the rest of the lines in the file.
Related
i have problems in searching a string in a file, insert a new line after the searched string and write on the new added line. currently i am using below code from examples and discussion i found:-
$target = '<18>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$string_i_am_looking_for] = $put;
file_put_contents( $filename , implode( "\n", $lines ) );
text file:-
<17>
<18>
<19>
<20>
at first action, i was able to put the $put in the text file.
<17>
<18>Enter
<19>
<20>
but, when i change the $target = "<20>", i was not able to write after the new $target. It will appear next to the first line. And when i reload the page more and more, it will keep on writing on the first line. Below is the result:-
<17>EnterEnterEnterEnterEnter
<18>Enter
<19>
<20>
Word Enter is not new line in any manner. You have to replace it with \r\n or \n (depends on file new line character).
$target = '<18>';
$put = "\r\n";
$file = 'line.txt';
Try This
$target = '<20>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$key = array_search($string_i_am_looking_for,$lines);
$toSearch = $target.$put;
if(!in_array($toSearch,$lines)) {
$lines[$key] = $target.$put;
}
file_put_contents( $filename , implode( "\n", $lines) );
How to delete / clear lines of data if it reaches 100th line. I checked some examples, but it is not working.
I need to check the number of the line end if it reaches line number 100, delete or clear all in that text file.
The following code is taken from an example, but this is also not working:
<?php
$text = "log.txt";
$lines = explode("\n", $text);
$lines = array_slice($lines, 0, 10); //10 is how many lines you want to keep
$text = implode("\n", $lines);
?>
Something like this: you will need to take it and fit it to your application, but I think this is what you are looking for.
//Count lines
$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
//Remove lines
if ($linecount ==100)
{
$lines = file($file, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);
}
I want to take one text file, split it in half, and put one half in one file, then the remaining half in the next. How would one accomplish this?
an example would be: split.php?n=file.txt
$file = $_GET['n'];
$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
$contents = fread($fp,$lengthhalf);
file_put_contents('./server/php/files/[2]'.$file,$contents);
$i++;
}
This does the work, without reading the whole file (or half of it) at once in memory:
function split_in_halves($file, $half1, $half2) {
$size = filesize($file);
$fd = fopen($file, 'rb');
stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');
I have a php file with the following info
One
Two
Three
Now i want to split them into an array, so i used:
$filehandle = fopen($filename, 'rb');
$line_of_text = fgets($filehandle);
$array = explode("\n", $line_of_text);
But it is not working.
They are written in the file like this:
$filehandle = fopen($textfile, 'a');
fputs($filehandle, $line . "\r\n");
fclose($filehandle);
So how do i read them into an array?.
Thanks.
I think you are looking for file(). However, it should be noted that this will leave all your array elements with a trailing CRLF sequence on them.
Alternatively (all these will strip the trailing CRLF):
$array = explode("\r\n", file_get_contents($filename));
...or...
$fp = fopen($filename, 'r');
$filecontents = fread($fp, filesize($filename));
$array = explode("\r\n", $filecontents);
...or...
$fp = fopen($filename, 'r');
$array = array();
while (($line = fgets($fp)) !== FALSE) $array[] = trim($line);
You should use the file function
file — Reads entire file into an array
$your_array = file ("filename", FILE_IGNORE_NEW_LINES); // add the flag to strip newlines
In PHP if you write to a file it will write end of that existing file.
How do we prepend a file to write in the beginning of that file?
I have tried rewind($handle) function but seems overwriting if current content is larger than existing.
Any Ideas?
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
$filename = "log.txt";
$file_to_read = #fopen($filename, "r");
$old_text = #fread($file_to_read, 1024); // max 1024
#fclose(file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Another (rough) suggestion:
$tempFile = tempnam('/tmp/dir');
$fhandle = fopen($tempFile, 'w');
fwrite($fhandle, 'string to prepend');
$oldFhandle = fopen('/path/to/file', 'r');
while (($buffer = fread($oldFhandle, 10000)) !== false) {
fwrite($fhandle, $buffer);
}
fclose($fhandle);
fclose($oldFhandle);
rename($tempFile, '/path/to/file');
This has the drawback of using a temporary file, but is otherwise pretty efficient.
When using fopen() you can set the mode to set the pointer (ie. the begginng or end.
$afile = fopen("file.txt", "r+");
'r' Open for reading only; place
the file pointer at the beginning of
the file.
'r+' Open for reading and
writing; place the file pointer at the
beginning of the file.
$file = fopen('filepath.txt', 'r+') or die('Error');
$txt = "/n".$string;
fwrite($file, $txt);
fclose($file);
This will add a blank line in the text file, so next time you write to it you replace the blank line. with a blank line and your string.
This is the only and best trick.