Find and edit text files via PHP - php

Let say a text file contain
Hello everyone, My name is Alice, i stay in Canada.
How do i use php to find "Alice" and replace it with "John".
$filename = "C:\intro.txt";
$fp = fopen($filename, 'w');
//fwrite($fp, $string);
fclose($fp);

$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);

Read the file into memory using fread(). Use str_replace() and write it back.

If its a big file, use iteration instead of reading all into memory
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"Alice")!==FALSE) ){
$line=preg_replace("/Alice/","John",$line);
}
print $line;
}
fclose($f);
}

Related

for loop looping to tlast item in text file

I been working trying everything to get this to work any help would be greatly apreciated.
i tried many couple of ways to get this work but i either get this error that the domain ame parameter is empty or I get the last domain in the txt file.
the txt file is just one domain per line.
$address="file.txt";
$shit=fopen($address,"r");
$contents2= fread($shit,filesize($address));
//also tried $domainlist=explode("\n\r",$contents2);
$domainlist=explode("\n",$contents2);
for($i=0 ; $i<=count($domainlist); ++$i){
$domainlist[$i]=$domain;
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver/WhoisService?
domainName=$domain&username=$username&password=$password&outputFormat=JSON");
$results=json_decode($contents);
print_r($results);
unset($domain);
};
?>
Easier:
$lines = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $domain) {
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver /WhoisService?domainName=$domain&username=$username&password=$password&outputFormat=JSON");
$results = json_decode($contents);
print_r($results);
}
You may want to trim($domain) or make sure it's valid or other checks before doing file_get_contents().
$file = fopen("file.txt", "r");
while(!feof($file)){
$line = fgets($file);
$last_line = $line;
}
fclose($file);
echo $last_line;
A few ways to do this...
$file = file("file.txt");
foreach($file as $line) {
// do something with the $line
}
I prefer this method unless you're unsure of the file size. If unsure, you may want to consider using fopen.

How can I add multiple strings to one text file, and read the all?

I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}

write the out put on file

I am very new to php, and i have search and put together this script to convert text to csv and write the out put on the file.
$File = "/var/apache2/htdocs/loginS/host.txt";
$Handle = fopen($File,"r");
$Content = fread ($Handle,filesize ($File));
fclose($File);
fclose($Handle);
$Content = explode("\t", $Content);
foreach($Content as $Value) {
//echo $Value."|"; // till this line working
fwrite($save, $Value);
fclose($save);
}
the problem is when I try to write on the file. I got only one line.what is my error.
You are calling fclose() on the file in your loop that is writing records. fclose() closes the file handle so it is no longer valid and cannot be written to.
Move fclose($save); after the } that ends the foreach() with your content.
Also, you could simplify things a bit by calling $Content = file_get_contents($File); since that is what you are doing in effect with fread(). Also, since $File is just a string variable, calling fclose() on it is unnecessary and doesn't do anything. You were correctly closing it by calling fclose() on $Handle. But using file_get_contents() will eliminate the need for both. The only file you would need is the one you were writing to.
Here is an example using the file() function which reads each line of a file into an array.
$file = '/var/apache2/htdocs/loginS/host.txt';
$content = file($file);
$save = fopen('./out.csv', 'w+');
foreach($content as $line) {
$line = rtrim($line, "\r\n"); // remove the newline from $line
$parts = explode("\t", $line);
$lineCsv = implode('|', $parts); // or ',' ?
fwrite($save, $lineCsv . "\n"); // write output to file
}
fclose($save);

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

PHP FILES reading and writing

Is it possible for me to read from / and write to the same file? If so, could you explain me
how to do that
Yes it is.
$file = "./test.txt";
// open file at the beginning.
$fh = fopen($file, 'r+');
//read the first line of the file. (advances pointer to the second line).
$contents = fread($fh);
// modify contents.
$new_contents = str_replace("hello world", "hello", $contents);
// make sure you're back at the 0 index.
fseek( $file, 0 );
// write
fwrite($fh, $new_contents);
// close.
fclose($fh);
// done!
In PHP 5 file_put_contents is the easiest way:
<?php
$file = 'people.txt';
$current = file_get_contents($file); // Open the file to get existing content
$current .= "John Smith\n"; // Append a new person to the file
file_put_contents($file, $current); // Write the contents back to the file
?>
file_put_contents("write.txt",file_get_contents("read.txt"));
Here is some documentation. You can see there all the parameters you can use in these functions.
http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fread.php
http://www.php.net/manual/en/function.fclose.php
http://www.php.net/manual/en/function.fwrite.php
http://www.php.net/manual/en/function.fseek.php

Categories