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
Related
How would I save an array to a binary file and then read that binary file back to an array in php?
This is where I am so far, but it doesn't work:
$arr = array("key1"=>"val1","key2"=>"val2","key3"=>"val3");
//save file
$file_w = fopen('binint', 'w+');
$bin_str = pack('i', $arr);
fwrite($file_w, $bin_str);
fclose($file_w);
//load file
$filename = "file.bin";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
$newarr = unpack('i*', $contents);
print_r($newarr);
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 am trying to open multiple files then split each file by line. I am using this with one foreach() to browse through files and another foreach() inside of it to split the file's lines.
$dir = '../mydir';
$files = scandir($dir, 1);
foreach($files as $input){
if(($input!==".")&&($input!=="..")){
$myfile="../mydir/".$input;
$fh = fopen($myfile, 'r');
echo $input."... ";
$input = substr($input,0,-4);
$FN = "../mydir/out.".$input.".xls";
$FH = fopen($FN, 'w') or die("Can't open file!");
$lines = file($myFile);
foreach($lines as $line) {
list($OPT1,$OPT2) = explode(",", $line);
fwrite($FH, $OPT1);
}
echo "Done.";
}
}
But my $OPT1 is empty.
I suspect your $fh = fopen($myfile,'r') is locking the file so file() can't access it. You don't appear to be using that file handle (indeed you are overwriting the variable later) so just remove that line and you should be good.
EDIT: Oh, and apparently variable names are case-sensetive. You can't interchange $myfile and $myFile.
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.
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.