Can't write csv to .txt file? PHP - 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);

Related

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

Create text file failed, error: failed to open stream: No such file or directory [duplicate]

This question already has answers here:
Encode or somthing to escape slash (/) input in php?
(1 answer)
Allowed characters in filename
(8 answers)
Closed 3 years ago.
I tried to create file on my xampp directory :
path : D:\ProgramFile\xampp\htdocs\pg_api
I already created one php file, create.php
This is the code :
<?php
$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);
?>
I ran the code and the file generated successfully, now what I want is to create a text file with name from variable :
This is what I tried :
<?php
$currentdate = date('d/m/Y_H:i:s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";
$myfile = fopen($filename, "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
I expected the file to be created with $filename as file name but an error on the browser page says:
Warning: fopen(id_1_29/10/2019_05:59:57.txt): failed to open stream:
No such file or directory in
D:\ProgramFile\xampp\htdocs\pg_api\create_1.php
(My error : here)
Anyone can tell me what's wrong with my code?
Windows do not allow special characters like /as a filename (it is not safe even in linux). Not just that, i will rather go with file name like id_1_29-10-2019_05-59-57.txt
To achieve the above filename:
$currentdate = date('d-m-Y_H-i-s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";
$myfile = fopen($filename, "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

Create new txt files from each line of a txt file

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.

PHP: Downloading 2 Created Text Files As Zip

I'm trying to create 2 text files which should only be placed in a downloadable zip file.
Twice use of
fopen("php://output","w")
with
header() things
works and helps avoiding file creation on server but I end up mixing the two strings to into one downloadable text file.
Here is a local version of creating 2 files in a local directory:
$dirname = "C:/texts";
if (!is_dir($dirname)) {
mkdir($dirname);
}
$myfile = fopen("C:/texts/one".$dateInputted.".txt", "w") or die("Unable to open file!");
fwrite($myfile, $one);
fclose($myfile);
$myfile = fopen("C:/texts/two".$dateInputted.".txt", "w") or die("Unable to open file!");
fwrite($myfile, $two);
fclose($myfile);
Use ZipArchive plugin of PHP
$zip = new ZipArchive();
$zip->open('path/to/zipfile.zip', ZipArchive::CREATE);
$zip->addFile('some-file.pdf', 'subdir/filename.pdf');
$zip->addFile('another-file.xlxs', 'filename.xlxs');
$zip->close();
You can find more help here :
http://akrabat.com/php/creating-a-zip-file-with-phps-ziparchive/
http://php.net/manual/en/zip.examples.php

read and execute commands from text file

I have a txt file with all the sql commands. I need to open the file, read the commands and execute against postgresql.
$file = fopen("createme.sql.txt", "r") or exit("Unable to open file!");
while(!feof($file))
{
pg_query($conn, fgets($file));
}
fclose($file);
I expected the above code to work. But is shows an error:
PHP Warning: pg_query(): Query failed:
How do I execute the commands from a text file?
fgets get file content line by line.
Using fread to get all content of file, set the second parameter to size of your files.
$fileName = "createme.sql.txt";
$file = fopen($fileName, "r") or exit("Unable to open file!");
// checking if opening file is error.
if(!feof($file))
{
$str = fread($file, filesize($fileName));
pg_query($conn, $str);
}
fclose($file);
Another trick thanks to #smassey
$fileName = "createme.sql.txt";
$str = file_get_contents($fileName);
pg_query($conn, $str);
fclose($file);
try trim() to cutoff "\r\n" from the end of each line
$file = fopen("createme.sql.txt", "r") or exit("Unable to open file!");
while(!feof($file))
{
pg_query($conn, trim(fgets($file)));
}
fclose($file);

Categories