Create new txt files from each line of a txt file - php

I have a various txt files like ex: dictionary , each new line is term and then description. pipe delimited.
I have wrote simple script that actually reads each line and then creates (fwrite) new txt file named after term and description as a text of that file.
It works but I'm wondering if there is a better approach, one that takes special characters into account, buffer perhaps, Not sure where to start.
$file = fopen("test.txt", "r") or exit("Unable to open file!");
// Output a line of the file until the end is reached
while(!feof($file))
{
$line = fgets($file);
// making all lowercase - optional
$line = strtolower($line);
// take the first value before delimiter
$var = substr( $line, 0, strpos( $line, '|' ) );
// remove some characters - optional ( depends on a file structure and contents )
$var = str_replace("-", "", $var);
// what txt should be written into a each new file
$txt = str_replace("|", "", $line);
// name the file
$myfile = fopen("$var.txt", "w") or die("Unable to open file!");
// write
fwrite($myfile, $txt);
//close each
fclose($myfile);
}
//close
fclose($file);
UPDATE
$file = fopen("test.txt", "r") or exit("Unable to open file!");
// Output a line of the file until the end is reached
while(!feof($file))
{
$line = fgets($file);
// #sorak fix
$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
// making it lowercase - optional for each
$line = strtolower($line);
$name = strtolower($name);
// what txt should be written into a each new file
$txt = str_replace("|", " ", $line);
// name the file
$myfile = fopen("$name.txt", "w") or die("Unable to open file!");
// write
fwrite($myfile, $txt);
// action echo
echo "$myfile - $name - $txt </br>";
//close each
fclose($myfile);
}
//close
fclose($file);
Since last update contained some duplicate code lines/bugs that caused skipping every other line :) I'm posting new fixed and bit upgraded version.
// this utility is for creating multiple names.txt files from separate lines in original.txt file
// format for original file is: is name|text
// increase memory limit to 32M
ini_set('memory_limit','32M');
// increase 1440 seconds = 24 minutes
ini_set('max_execution_time', 1440);
$file = fopen("original.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
// #sorak fix
//$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
// making it lowercase - optional for each
$line = strtolower($line);
$name = strtolower($name);
$filename = $name . ".txt";
// what text should be written into a each new file
// change pipe separator if needed
$txt = str_replace("|", " ", $line);
// set values
$myfile = fopen($filename, "a") or die("Unable to open file!");
$dir = "/example.com/could_be_dynamic_folder_name";
// write
fwrite($myfile, $txt);
// chmod($dir,0777); optional if creation of dir is from GET/other value and not in the same parent
// action echo
echo "$myfile </br>";
echo "$dir/$filename </br>";
echo "$txt </br></br>";
// chmod
chmod($dir,0777);
chmod("$dir/$filename",0666); // remember to set this script to 0666
}
fclose($file);
} else {
// error echo
echo "something went wrong, error";
}
Works like a charm now. Case closed.

$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
Explode makes splitting up the string easier, and with the [0] we grab the first piece. That preg_replace instruction just removes all characters that aren't letters or numbers.

Related

Overwrite line in a file if it contains a string [duplicate]

This question already has answers here:
Overwrite Line in File with PHP
(7 answers)
Closed last year.
I am trying to overwrite a line in PHP in a file if it contains a certain string. When I write to my file, the lines aren't overwritten but are appended to the end. I am opening the file as 'a+', not 'w+' as I don't want the settings of other 'modes' to be removed.
The file, for example:
mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
I have tried:
$myfile = fopen("test.txt", "a+") or die("Unable to open file!");
$lines = explode("\n", $myfile);
$exclude = array();
foreach ($lines as $line) {
if (strpos($line, 'mode1') !== FALSE) {
continue;
}
$exclude[] = $line;
}
echo implode("\n", $exclude);
$txt = "mode1Hello= 900\n";
fwrite($myfile, $txt);
$txt = "mode1Goodbye= 800\n";
fwrite($myfile, $txt);
$txt = "mode1=Neutral 700\n";
fwrite($myfile, $txt);
fclose($myfile);
But the test.txt file now reads:
mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700
But I would like it to read:
mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
$filename = 'test.txt';
$contents = file_get_contents($filename);
$lines = explode("\n", $contents);
foreach ($lines as &$line) {
if (str_starts_with($line, 'mode1Hello=')) {
$line = 'mode1Hello= 900';
} elseif (str_starts_with($line, 'mode1Goodbye=')) {
$line = 'mode1Goodbye= 800';
} elseif (str_starts_with($line, 'mode1Neutral=')) {
$line = 'mode1Neutral= 700';
}
}
unset($line);
$result = implode("\n", $lines);
file_put_contents($filename, $result);

Php: I can add lines to the text file, but I can't delete them

I am working on linux (raspbian). Code works locally, but not on the server.
I can't understand what the problem is in the code. The addLineToFile function works perfectly, while deleteLineFromFile does not.
I call the functions with:
if (isset($_POST['delete'])){
$valTemp = $array[$_POST['delete']];
addLineToFile($directory."linkOffline.txt",$valTemp);
deleteLineFromFile($directory."output.txt",$valTemp);
}
where
$directory = "/home/pi/linkFinder/server/";
then
function addLineToFile($dirFile, $line){
$myfile = fopen($dirFile, "a") or die("Unable to open file!");
fwrite($myfile, "\n". $line);
fclose($myfile);
}
function deleteLineFromFile($dirFile, $line){
$contents = file_get_contents($dirFile);
$contents = str_replace($line."\r\n", '', $contents);
file_put_contents($dirFile, $contents);
}
I tried to assign all the permissions to the txt files, with chmod 777.
I also thought there might be some problem with file_get_contents and file_put_contents. So I rewrote the function like this, but it still doesn't work.
function fileGetContents2($url) { //alternativa a file_get_contents
$file = fopen($url, 'r');
$data = stream_get_contents($file);
fclose($file);
return $data;
}
function deleteLineFromFile($dirFile, $line){
$contents = fileGetContents2($dirFile);
$contents = str_replace($line."\r\n", '', $contents);
$myfile = fopen($dirFile, "w") or die("Unable to open file!");
fwrite($myfile, $contents);
fflush($myfile);
fclose($myfile);
}
The txt files are in a /home/user/... folder and are generated by a python script.
Thanks in advance

Can't write csv to .txt file? PHP

I am trying to use the putcsv function in php to write an array to a text file but the file is blank, I tried changing the extension to .csv and it works but I need to write it to .txt as per specifications of my assignment. I attempted to change the filename to .csv then write to it then back to .txt, my filesize changed but the file is still blank.
Here is my code
$fp = fopen('logfile.txt','w') or die ('No file!!!');
fputcsv($fp,$csv);
fclose($fp);
I got your problem, if its not allow to write CSV format to text file then write in to CSV file and rename(using rename() in PHP) to text file after writing in to CSV is done.
Here is my sample code:
$fp = fopen('logfile.csv','w') or die ('No file!!!');
fputcsv($fp,$csv);
fclose($fp);
rename('logfile.csv','logfile.txt');
Let me know, if your problem is solved.
Second Method:
str_putcsv()
function str_putcsv($fields, $delimiter = ',', $enclosure = '"', $escape_char = '\\' ) {
foreach ($fields as &$field) {
$field = str_replace($enclosure, $escape_char.$enclosure, $field);
$field = $enclosure . $field . $enclosure;
}
return implode($delimiter, $fields) . "\n";
}
Simply you can call
$file = fopen("newfile.txt", "w") or die("Unable to open file!");
$csvStr = str_putcsv($csv);
fwrite($file, $csvStr);
fclose($fp);
Use fwrite()
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

How to insert string before last line?

I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4
example line1
example line2
//i need insert here
lastline $eg};
My code is working but this is adding empty lines after all lines :
$filename = 'example.php';
$arr = file($filename);
if ($arr === false) {
die('Error' . $filename);
}
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here
$person = "my text here\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here
$file = "tmp/saf.txt";
$fc = fopen($file, "r");
while (!feof($fc)) {
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose($fc);
//open same file and use "w" to clear file
$f = fopen($file, "w") or die("couldn't open $file");
$lineCount = count($lines);
//loop through array writing the lines until the secondlast
for ($i = 0; $i < $lineCount- 1; $i++) {
fwrite($f, $lines[$i]);
}
fwrite($f, 'Your insert string here'.PHP_EOL);
//write the last line
fwrite($f, $lines[$lineCount-1]);
fclose($f);

How do I prepend file to beginning?

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.

Categories