how to skip empty lines from a txt file with php - php

I am using this code to delete an email address form a txt file named database-email.txt:
// unsubscribe
if (isset($_POST['email-unsubscribe'])) {
$emailToRemove = $_POST['email-unsubscribe'] . ',';
$content = file_get_contents('database-email.txt');
if($content = str_replace($emailToRemove, '', $content)) {
echo "$emailToRemove successfully removed!";
}
else {
echo "$emailToRemove could not be removed!";
}
file_put_contents('database-email.txt', $content);
}
?>
My txt file looks like this:
annelore#mail.ru,
francien#live.nl,
frans#moonen.nl,
harry#hotmail.com,
jannie#live.nl,
jeanette.schmitz#live.nl,
johnny.doe#live.nl,
I tried this to skip all the empty lines in the txt file but without success:
file_put_contents('database-email.txt', implode(PHP_EOL, file($content, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));
How can i skip the empty lines from database-email.txt ?

Use the file() function with FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES options to read the file as an array. Then use the array_search() function to search for the element and remove it if it's present. You can then implode the array and write it back to file.
Don't use your str_replace approach, it's buggy. Imagine this is your file:
abdc#domain.com
If you remove dc#domain.com you will get:
ab
You are not checking that you are replacing an entire email.
I would also suggest that you remove the commas, you don't need them if you have only one email per line.

You could try something like this :
file_put_contents('database-email.txt',
str_replace("\n\n", "\n", file_get_contents('database-email.txt'))
);
NB \n depends of how you inserts lines in your file. It could be \r\n or PHP_EOL.

This should do the trick:
file_put_contents('database-email.txt', implode('', file($content, FILE_SKIP_EMPTY_LINES)));
Alternatively:
file_put_contents('database-email.txt',preg_replace('~[\r\n]+~',"\r\n",trim($content)));

Related

add string to text file with verification

I have a code:
$fp = fopen("/path/to/file", "w");
fwrite($fp, $var);
fclose($fp);
I need to do - add text string write in a text file without spaces with verification sample text.txt
foo
bar
foo_bar
If foo already exist in file - nothing to add.
Add a line of text in a file, but with check, if text is already there, example foo there is then nothing to add. If i add foofoo add it to text.txt
One way is to read into an array and check for the value. If it doesn't exist, append it (with a newline \n):
$lines = file("/path/to/file", FILE_IGNORE_NEW_LINES);
if(!in_array($var, $lines) {
file_put_contents("/path/to/file", "\n$var", FILE_APPEND);
}

file_put_contents inside a while

Is it possible to put the file_put_contents() function inside a while() loop?
I am trying to get my script to write lines into a text file - there's over 4 thousand lines to write.
$glassquery = $db->query("SELECT item FROM glass");
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL);
}
So it's writing the item name into the text file then the next one on a new line.
I think what you want is the FILE_APPEND flag:
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL, FILE_APPEND);
}
This will write the lines one at a time without erasing previous lines.

PHP Add string to line 2

I want to add a string (the value of a DOM element - $entry = stripslashes($_GET["nameofmytextarea"]);) to the second line of myfile.csv (so as not to delete the header).
I don't care about CSV stuff, everything is already formatted. Just treat it as a text string being added to a text file.
I don't want anything complicated, just skip the first line and "append" above the second line: under the header but above all the other CSV lines.
How hard can that be?
$contents = explode("\n", file_get_contents('myfile.csv'), 2);
file_put_contents('myfile.csv', $contents[0]."\n".$entry."\n".$contents[1]);
This should work if the lines are separated by unix-lineendings.
If the file first looks like this:
header
content
content2
and the code is run with $entry = 'test'; it will look like this afterwards:
header
test
content
content2
A combination of file() and array_splice() is what you need here:
function prepend_to_csv ($file, $line) {
if (!$data = file($file)) {
return FALSE;
}
array_splice($data, 1, 0, $line.PHP_EOL);
return (bool) file_put_contents($file, $data);
}
if (prepend_to_csv('myfile.csv', "this,is,some,data")) {
echo 'Success';
} else {
echo 'Fail';
}
Because of the way this method works, you need to ensure that you manually add the EOL to the new line yourself.

How do I read a text file line by line?

suppose I do have a text file with these lines
name: Mathew
Age : 32
Country : USA
Location : California
bla bla bla....
What I want is I want a php code which can read this file and display result to a webpage.
Use this code (untested):
$fp = fopen('filename.php');
while (!eof($fp)) {
$line = fgets($fp);
// Add code to display the values how you want
echo $line."<br>";
}
fclose($fp);
That will loop through the file line by line. Each line will be assigned to the $line variable, and then you can manipulate and display the values how you would like.
file() function reads a file into an array where one element represents a string in the file
Display the actual text or remove the name:, etc?
Use the file() function (tutorial?) to read the file in and then echo out / process each line.

How to update an ini file with php?

I have an existing ini file that I have created and I would like to know if there was a way to update a section of the file or do I have have to rewrite the entire file each time?
Here is an example of my config.ini file:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
Say I want to change the [positions] top=false. So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file. Or is there a way just to change that section?
I used the first suggestion of you:
So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file
function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
$config_data[$section][$key] = $value;
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}
If you use the PHP INI functions, you must rewrite the file each time.
If you write your own processor, you could (with limitations) update in place. If your insertions are longer or shorter than your deletions, you'll have to rewrite the file anyhow.
This is a perfect example of when you could use regular expressions to replace a string of text. Check out the preg_replace function. If you're not quite sure how to use regular expressions you can find a great tutorial here
Just to clarify you'll need to do something like this:
<?php
$contents = file_get_contents("your file name");
$contents = preg_replace($pattern, $replacement, $contents);
$fh = fopen("your file name", "w");
fwrite($fh, $contents);
?>
Where $pattern is your regex to match and $replacement is your replacement value.

Categories