Writing a string array to text file separated by new line character - php

I have a PHP page which accepts input from user in a text area. Multiple strings are accepted as input from user & would contain '\n' and I am scanning it as:
$data = explode("\n", $_GET['TxtareaInput']);
Each string should be moved into the text file with new line character separation. This is the code I am using now and it separates each string with a '^M' character:
foreach($data as $value){
fwrite($ourFileHandle, $value);
}
Is there anyway I can get each string followed by a carriage return?

You can simply write it back using implode:
file_put_contents('file.csv', implode(PHP_EOL, $data));

Try this:
$data = explode("\n", $_GET['TxtareaInput']);
foreach($data as $value){
fwrite($ourFileHandle, $value.PHP_EOL);
}

If you want to add new lines, then why are you first removing them?
$data = explode("\n", $_GET['TxtareaInput']);
Keep only this line:
fwrite($ourFileHandle, $data);
It will write your data to the file as it was received.
If you want to replace all new lines by carriage returns before writing to file, use this code:
fwrite($ourFileHandle, str_replace("\n", "\r", $data));

Related

trim function not working for string array

This is a really odd behavior that I can't explain. I have a CSV file that I'm trying to format. The lines could have trailing ','s that I want to remove.
$lines = explode(PHP_EOL, $csv);
$csv = '';
foreach($lines as $line) {
$csv .= trim($line, ',') . PHP_EOL;
}
The trim is not doing anything and just returning the line back as it is. Just to make sure I copied a line from the csv trim("a,b,c,d,,", ','); which works fine. Can anyone tell me why the above code won't work?
If the CSV file was created on a different operating system, it may use different line breaks than PHP_EOL. So trim any line break characters in addition to commas.
foreach($lines as $line) {
$csv .= trim($line, ",\r\n") . PHP_EOL;
}
Don't manually edit the CSV file. Parse it into an array, then edit the array. Then you can write the modified array back to a CSV file.
You can use fputcsv to write the data to a file, or str_putcsv (a custom function).
$newData = [];
$data = array_map('str_getcsv', $lines); // parse each line as a CSV
foreach ($data as $row) {
$row = array_filter($row); // remove blank values
// for some dumb reason, php has `str_getcsv` but not `str_putcsv`
// so let's use `str_putcsv` from: https://gist.github.com/johanmeiring/2894568
$newData[] = str_putcsv($row);
}
$newData = implode(PHP_EOL, $newData);

How do I put content on second line in .txt file and read it

For storing values in a .txt file I use this code:
file_put_contents('data/vote_result.txt', implode(',', $results));
and for reading i use this:
$results = explode(',', file_get_contents('data/vote_result.txt'));
The content of vote_result.txt looks like this: 0,1,2,3
How can I store a second line in the same .txt file so that the content looks like this:
0,1,2,3
0,1,2,3
and how can I read that second line?
Read second line:
$myFile = "data/vote_result.txt";
$linesArray = file($myFile);
echo $linesArray[1]; //line 2
If you want to append a line to file, use FILE_APPEND flag in file_put_contents and concatenate "\n" with implode.
file_put_contents('data/vote_result.txt', implode(',', $results)."\n", FILE_APPEND);
Besides that you should use a database like MySQL for this, you can use the file function. Example:
$data = file('file.txt');
print $data[1]; // printing out the second line
This given you can simply add new lines just by adding a new entry in the array and then implode it with the newline character and save it via the file_put_contents function.
$content = implode("\n", $data);
file_put_contents('file.txt', $content);

php - eliminate the space in the beginning while writing to CSV file

I am writing array values to a CSV file using PHP. In the array values, I have included a line break using \n. After the array values are updated, I am using the implode function as below.
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
However, while writing to the CSV file, an extra space gets appended to the front of the line. This is causing me some problems in display. I want to eliminate the space in front of the line while it is getting written. I tried to do the below.
$line1 = str_replace(' .','.',$line);
However, I am not able to write without the space in beginning to the CSV file.
You don't need to use spaces at all:
$newLine[] = $row[$i].",";
$csv2 [] = implode("\n", $newLine);
$csv2[] = trim ( implode("\n", $newLine) , "\n");
This should work since it removes only line breaks at the beginning and end of the string.

remove everything after first space on each line of this text file

In PHP, how can one edit a text file and save it so that everything after the first space is removed?
In other words, so that each line only has its first word?
For example, if the text file looked like this:
Adi NNP
Adia NNP
Adios NNP FW
Adios-Direct NNP
Adios-On NNP
Adios-Rena NNP
Adios-Trustful NNP
Adirondack NNP
Adirondacks NNPS
Adjoining VBG
Adjournment NN
after executing the script, the text file would look like this:
Adi
Adia
Adios
Adios-Direct
Adios-On
Adios-Rena
Adios-Trustful
Adirondack
Adirondacks
Adjoining
Adjournment
How I would approach this would be to open the file, read it in, and take each line and store it in an array. Then replace everything after the first space with nothing. And lastly, save the edited array to a new file.
Is there a better way to do it than that?
All I know how to do in the above method is everything except the last two tasks. I would do it like so:
$file = array();
$lines = file('file.txt');
foreach($lines as $line){
array_push($file, $line);
}
// now travel through $file and replace everything after first space with nothing
// travel though $file again, but write each element as a new line in a .txt file
You can use explode() to separate the line by spaces. Then you can immediately write the string back to a file, no second loop is required:
$file = array();
$lines = file('file.txt');
$new_file = fopen('new.txt', 'w+');
foreach($lines as $line){
$bits = explode(' ', $line);
fwrite($new_file, $bits[0] . PHP_EOL);
}
fclose($new_file);
You can do it in the same line: just replace array_push($file, $line) with...
$file[] = strtok($line, ' ');
It can be written even more compact with help of array_map:
$lines = array_map(function($line) {
return strtok($line, ' ');
}, file('file.txt'));
... or you can write it back immediately, as shown in #hek2mgl answer.
You can bypass arrays entirely and do this with a simple regular expression:
// Read in contents into a variable
$data = file_get_contents('input.txt');
// Drop the space and everything after on each line
$data = preg_replace('/ .*$/m', '', $data);
// Dump contents to file (change this to input.txt if you want to overwrite the file)
file_put_contents('output.txt', $data);

PHP extract data from text file and write to another file

This is my first post on the internet for some assistance with coding so please bear with me!
I have been finding open code on the internet for a few years and modding it to do what I want but I seem to have come up against a wall with this one that I am sure is very simple. If you would please be able to help me it would be very much appreciated.
I have the following page:
<?php
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis)
{
foreach($inthis as $pos => $a){
}
$newarr = implode("\r\n", $inthis);
$fh = fopen("example.txt", "w");
fwrite($fh, $newarr);
fclose($fh);
}
modFile(4, '', $f);
I have a file (all.txt) with the following:
11111111111, 22222222222, 33333333333, 44444444444
That I wish to display like this:
11111111111
22222222222
33333333333
44444444444
and to add a space then some text after each number where the text is the same on each line:
11111111111 text here
22222222222 text here
33333333333 text here
44444444444 text here
I have an html form that passes the custom text to be appended to each line.
I need to keep the file all.txt intact then save the newly formatted file with a different name.
I have tried putting variables into the implode where I currently have the "\r\n" but this does not work.
Any help very much appreciated.
Thanks in advance!
A few notes about your code: You are passing $pos to the function but it will get overwritten in the foreach. Also the foreach is empty, so what's it good for? And I don't see you use $text anywhere either.
To achieve your desired output, try this instead:
file_put_contents(
'/path/to/new.txt',
preg_replace(
'/[^\d+]+/',
' some text' . PHP_EOL,
file_get_contents('all.txt')
)
);
The pattern [^\d+]+ will match any string that is not a consecutive number and replace it with "some text " and a new line.
A somewhat more complicated version achieving the same would be:
file_put_contents(
'/path/to/new.txt',
implode(PHP_EOL, array_map(
function ($number) {
$message = filter_var(
$_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS
);
return sprintf('%s %s', trim($number), $message);
},
array_filter(str_getcsv(file_get_contents('/path/to/all.txt')))
)
));
This will (from the inside out):
Load the content of all.txt and parse it as CSV string into an array. Each array element corresponds to a number.
Each of these numbers is appended with the message content from the POST superglobal (you dont want to use REQUEST).
The resulting array is then concatenated back into a single string where the concatenating character is a newline.
The resulting string is written to the new file.
In case the above is too hard to follow, here is a version using temp vars and no lambda:
$allTxtContent = file_get_contents('/path/to/all.txt');
$numbers = array_filter(str_getcsv($allTxtContent));
$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
$numbersWithMessage = array();
foreach ($numbers as $number) {
$numbersWithMessage[] = sprintf('%s %s', trim($number), $message);
};
$newString = implode(PHP_EOL, $numbersWithMessage);
file_put_contents('/path/to/new.txt', $newString);
It does the same thing.
Your foreach() closing brace is on the wrong place. You've missed the exact part of running the execution of the new file creation. Here:
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis, $text){
$fh = fopen("example.txt", "w");
foreach($inthis as $pos => $a){
$newarr = $a." ".$text."\r\n";
fwrite($fh, $newarr);
}
fclose($fh);
}
modFile(4, "", $f, $text);
This is for formatting your new file as you desire, however, you're not passing the new $text['message'] you want to append to your new file. You could either modify your mod_file() method or pass it within the foreach() loop while it runs.
EDIT* Just updated the whole code, should be now what you aimed for. If it does, please mark the answer as accepted.

Categories