This script for write to a file from php :
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'a');
$Data = "Jane Doe\n";
fwrite($Handle, $Data);
$Data = "Bilbo Jones\n";
fwrite($Handle, $Data);
print "Data Added";
fclose($Handle);
?>
How to configure align the text like in fpdf (example : $pdf->Cell(20,10,'Title',1,1,'C');) ?
Use str_pad to get a decent result. Say you have 2 rows of data. Like:
Firstname, Lastname
If you want to sort these in a txt file to look nice you can do:
$firstname = "Jane";
$lastname = "Doe";
$firstname = str_pad($firstname, 30); //Force string to be 30 characters length
str_pad will add an amount of spaces to your string untill it reaches the length you want it to. Having all First names at exactly 30 characters will make the Last names appear perfectly sorted behind them as if you're having 2 lists in your TXT file.
Ofcourse if you ever want to read out the file you probebly want to trim away all those unnessary spaces. You can do this with:
$firstname = preg_replace('/\s+/', ' ', $firstname);
Related
I'm trying to read in a name from a text file in PHP and remove spaces in the names, which I do using preg_replace in a function.
function fixName($input) {
$input = preg_replace('/[^ \w-]/', ' ', $input);
return $input;
}
echo fixName('BOB VAN'), "\n";
However, I have a text file that has multiple names similar to the one above each on a new line, and I'm trying to figure out how to store those names that are read in from the file and process and output them. Would I do something such as reading the file and storing them into an array?
The text file looks like this
ID FIRST LAST
348 BOB VAN
349 ALBERT JOHN
If you want to read file string by string and store it in an array then you can try something like:
$output = array();
$handle = fopen("file.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle);
$buffer = preg_replace('/[^ \w-]/', ' ', $buffer);
list($id, $name) = explode(' ', $buffer, 2);
$output[$id] = $name; //you can index elements by ID or store ID and name as nested array
}
fclose($handle);
var_dump($output);
I'm trying to parse csv using str_getcsv in the following manner however I'm running into two problems (below).
$url = 'http://my.events.calendar/api/csv?mycalendarquery';
$response = wp_remote_get($url);
$response_body = $response['body']; // this is a really long string
$parsed_string = str_getcsv($response_body, ',', '"');
$full_events_array = array_chunk($parsed_string, 11);
Problem 1 - I can't use explode because one of the fields in the csv is "Description" which contains many/lengthy prose descriptions of events. Naturally these include commas, new lines, returns, etc...
Problem 2 - This is the one I have a question about. The categories (headers?) for the csv file are "Subject", "Date", (more things here...) "Description", "Calendar Address". However the last one doesn't have a comma after it. So, the entries for "Subject" and "Calendar" address are being combined like this -
array(11) {
[0] =>
string(32) "Calendar Address
"Application Due"" // this pattern happens for every event but with a url instead.
// Yes, I know this looks wrong in the code block, but this is exactly how the data is coming in (complete with the double quotes).
How do I parse this so that Calendar Address and Application Due are separated?
For reference, I've also tried str_getcsv($response_body, '"', ','); str_getcsv($response_body, ',', '"', '\n'); and several other combinations. Thanks for the help!
This script will read the CSV file into 251 rows of 12 elements each.
<?php // demo/temp_44414553.php
/**
* https://stackoverflow.com/questions/44414553/parsing-csv-where-the-last-header-is-followed-by-a-space?noredirect=1#comment75830321_44414553
*/
error_reporting(E_ALL);
// UNABLE TO ACCESS: http://events.uconn.edu/exports-2017-05-31-2017-07-01.csv
// COPY MADE HERE FROM THE DOWNLOAD LINK
$url = 'storage/exports-2017-05-31-2017-07-01.csv';
$csv = file_get_contents($url);
echo $csv;
$fpr = fopen($url, 'r');
if (!$fpr) trigger_error("Unable to open $url", E_USER_ERROR);
$kount = 0;
while (!feof($fpr))
{
$row = fgetcsv($fpr);
$kount++;
if (!$row) break;
echo PHP_EOL . count($row);
}
echo PHP_EOL . "There are $kount rows in the CSV at $url";
I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).
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.
I have file with contents:
Tom TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student
Tom1 TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student
Tom2 TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student
I have many lines like this.
Each line is having a name followed by a string untill end of the line.
I want to have a php script that will read first words keeps in a temp variable.
similarly I want all the text upto the end of the line to be going to the second variable.
I have used these
$myFile = "profiles.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
but the issue with that is I am able to read the first 5 characters. I want to read first time only one word. second one is all string to be going to a variable.
Something like this?
$myFile = "profiles.txt";
$fh = fopen($myFile, 'r');
$anArray = array();
while (($line = fgets($fg)) !== false) {
list($name, $restOfLine) = explode(' ', $line, 2);
// Do something with $name and $restOfLine (e.g. put them in array)
$anArray[] = array('name' => $name, 'line' => $restofLine);
}
fclose($fh);
var_dump($anArray);