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.
Related
I try to read all *.txt files from a folder and write all content from each file into another txt file. But somehow it only writes one line into the txt file.
I tried with fwrite() and file_put_contents(), neither worked.
Here is my code:
<?php
$dh = opendir('/Applications/XAMPP/xamppfiles/htdocs/test/');
while($file = readdir($dh)) {
$contents = file_get_contents('/Applications/XAMPP/xamppfiles/htdocs/test/' . $file);
$dc = array($contents);
}
file_put_contents('content.txt', $dc);
?>
This should work for you:
(Here I get all *.txt files in a directory with glob(). After this I loop through every file with a foreach loop and get the content of each single file with file_get_contents() and I put the content into the target file with file_put_contents())
<?php
$files = glob("path/*.txt");
$output = "result.txt";
foreach($files as $file) {
$content = file_get_contents($file);
file_put_contents($output, $content, FILE_APPEND);
}
?>
try this
$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
array_push($line, $contents);
}
//File path of final result
$filepath = "mergedfiles.txt";
$out = fopen($filepath, "w");
//Then cycle through the files reading and writing.
foreach($filepathsArray as $file){
$in = fopen($file, "r");
while ($line = fgets($in)){
print $file;
fwrite($out, $line);
}
fclose($in);
}
//Then clean up
fclose($out);
return $filepath;
I want to filter one text file by writing the results to a second text file.
I have a little bit of code and it doesn't work like it should work, it is only writing the LAST line of the first text file into a separate backup text file.
Code:
//filter the ingame bans
$search = "permanently";
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file
$file = fopen($logfile, "r");
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
{
$cache_ig = "ingamebanlist.txt";
$fh = fopen($cache_ig, 'w') or die("can't open file");
$content = "\n";
fwrite($fh, $content);
$content = $line;
fwrite($fh, $content);
fclose($fh);
}
}
I personally do not see any errors in my code, please help.
REMEMBER: It does kind of work, but it only writes the LAST line of the ban_list.txt file into the ingamebanlist.txt file...
What happens with your code is that you open(using write mode), write and close inside your loop so it will only ever write 1 entry then overwrite it until the last entry, thus only saving the last item.
What you want is to have it outside the loop like this:
<?php
$search = "permanently";
$logfile = "ban_list.txt";
$cache_ig = "ingamebanlist.txt";
$timestamp = time();
$read = fopen($logfile, "r") or die("can't read file");
$write = fopen($cache_ig, 'w') or die("can't write to file");
while(($line = fgets($read)) !== false)
{
if(stristr($line,$search))
{
fwrite($write, $line . "\n");
}
}
fclose($write);
fclose($read);
An alternative solution would be to use a instead of w at your fopen since w will:
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
While a will:
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
Which would allow your code to work as is without any changes but the line:
$fh = fopen($cache_ig, 'w') or die("can't open file");
To:
$fh = fopen($cache_ig, 'a') or die("can't open file");
I am using the following file read
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
problem is file.txt is generating dynamically and is in different folder so how do I call it in fopen ?
I am trying
$fh = fopen(/path/to/$myFile, 'r');
but obviously its not working and giving me error
PHP Parse error: syntax error, unexpected '/',
how to rectify this and include my path ?
This is a simpler way:
$theData = file_get_contents("/path/to/file/" . $myFile);
First off, it'd be simper just to use file_get_contents()
As to the file path, that needs to be a string, i.e.:
$fh = fopen("/path/to/".$myFile, 'r');
$myPath = "/path/to/file/";
$myFile = "file.txt";
$fh = fopen($myPath.$myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
I haven't tested it, but I guess it will work that way...
I have tried to solve this problem in my own way. Hope this will help you.
<?php
$myFile = "folder/file.txt";
$myHandle = fopen($myFile, "r");
$myData = fread($myHandle, filesize($myFile));
$rows = explode(" ", $myData);
foreach($rows as $row)
{
print $row;
}
fclose($myHandle);
?>
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.