I have a text file, more of a users file for a program. Im trying to use PHP to insert new data before groups: in the file. The last user is above this line and i want to insert new users below the last user and above groups: in the file
Ive been tinkering and was trying some things, but i can only get it after that line.
heres what i have
$key = 'groups:';
$newline = 'blackberry';
//copy file to prevent double entry
$file = "data2.yml";
$newfile = "filetemp.txt";
copy($file, $newfile) or exit("failed to copy $file");
//load file into $lines array
$fc = fopen ($file, "r");
while (!feof ($fc))
{
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose ($fc);
//open same file and use "w" to clear file
$f=fopen($newfile,"w") or die("couldn't open $file");
/* uncomment to debug */
print_r($lines);
print "\n";
//loop through array using foreach
foreach($lines as $line)
{
fwrite($f,$line); //place $line back in file
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n");
} //place $line back in file
}
fclose($f);
copy($newfile, $file) or exit("failed to copy $newfile");
?>
Its a yml file, so i cant add an extra line to post after or it screws up and refuses to run.
thanks!
your foreach code should be:
foreach($lines as $line)
{
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n"); //insert data before line with key
}
fwrite($f,$line); //place $line back in file
}
This way you will write the new data first then the original data.
Related
I have it where it prints the file to the body but I need to do that but have the file's data load from the last line to the first.
The code I have right now
$file = fopen('text.txt','r');
while ($line = fgets($file)) {
echo($line);
}
fclose($file);
Use file() to read the file into an array of lines. Then you can reverse the array and loop through it.
$lines = file('text.txt');
$lines = array_reverse($lines);
foreach ($lines as $line) {
echo $line;
}
I want to add string text (ip adress) in end of file if not exist.
I have a database with IP Adress, I want to add ip if not exist in my text file.
$rows=mysql_num_rows($resultcheck);
$fields=mysql_num_fields($resultcheck);
for ($i=0;$i<$rows;$i++){
for($j=0;$j<$fields;$j++){
//echo '<b>Date : </b>'.date("Y-m-d").' IP : ';
//echo long2ip(mysql_result($resultcheck,$i,$j)).'<br>';
$file=fopen("ff.txt","a+");
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
$line=file('ff.txt');
foreach($line as $line){
$arr=explode(':',$line);
if ($arr[0] != long2ip(mysql_result($resultcheck,$i,$j))){
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
}
}
}
}
For add strings to end of file open file with flag "a"
For compare string - you can open file with function file. It return array of lines in file. For find similar string just use foreach by this array from file.
In other words - show your code
Read line by line from file
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Append to file
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
I have the following code to write data to a text file.
$somecontent = "data|data1|data2|data3";
$filename = 'test.txt';
// Let's make sure the file exists and is writable first.
IF (IS_WRITABLE($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
IF (!$handle = FOPEN($filename, 'a')) {
PRINT "Cannot open file ($filename)";
EXIT;
}
// Write $somecontent to our opened file.
IF (!FWRITE($handle, $somecontent)) {
PRINT "Cannot write to file ($filename)";
EXIT;
}
PRINT "Success, wrote ($somecontent) to file ($filename)";
FCLOSE($handle);
} ELSE {
PRINT "The file $filename is not writable";
}
Now I want this text file to only every have 10 lines of data and when a new line of data is added which is unique to the other lines then the last line of data is deleted and a new line of data is added.
From research I have found the following code however total no idea how to implement it on the above code.
check for duplicate value in text file/array with php
and also what is the easiest way to implement the following code?
<?
$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($I=0;$i<count($inp)-1);$i++)
fwrite($out,$inp[$I]);
fclose($out)l
?>
Thanks for any help from a PHP newbie.
$file = fopen($filename, "r");
$names = array();
// Put the name part of each line in an array
while (!feof($file)) {
$line_data = explode("|", $fgets($file));
$names[] = $line_data[0]
}
$data_to_add = "name|image|price|link"
$data_name = "name" // I'm assuming you have this in a variable somewhere
// If the new data does not exist in the array
if(!in_array($data_name, $names)) {
unset($lines[9]); // delete the 10th line
array_unshift($lines, $data_to_add); // Put new data at the front of the array
// Write the new array to the file
file_put_contents($filename, implode("\n", $lines));
}
I need to dynamically add in the img src full file path to a file from a .txt file. So far i have been using the below code to populate titles, and descriptions:
< ?php
$myFile = "film_music/feature1.txt";
$lines = file($myFile);//file in to an array<br />
echo $lines[0]; //line 1
? >
The feature file contains all details for movies that will eventually be displayed here:
http://www.londonosophy.com/film_music2.php
Currently the file contains the following rows:
Sightseers (2012)
Dark comedy, featuring Alice Lowe
images/Sightseers-TinaPencil.jpg
Does anyone know php code that can read line X (or line 3 in this case) and dynamically populate the img src="" file path?
Many thanks in advance for your suggestions!
If you need to iterate over lines and need to check if line contains file path (for example, if sometimes there are white lines between blocks and sometimes they are missing), then:
<?php
$myFile = 'film_music/feature1.txt';
$lines = file($myFile);
$needle = 'images/';
$needleLen = strlen($needle);
foreach ($lines AS $line) {
$line = trim($line);
if (substr($line, 0, $needleLen) == $needle) {
echo '<img src="' . $line . '" alt="" />';
}
}
?>
You need to fetch 3rd line of the file every time, because it contains that path of the image.
<?php
global var $raw;
$myFile = "film_music/feature1.txt";
// open file...
$lines = file($myFile);//file in to an array<br />
for($i=2;$i<=no_of_lines;$i+3){
$raw = $lines[$i];
}
// Populate $raw variable where you need.
?>
Use $fh = fopen(...) and loop every line.
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
[do your things.]
}
http://www.php.net/manual/en/function.fopen.php
You can read each line of text line as:
$lines=file('file.txt');
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
if you don't need any special processing, this should do what you're looking for
$lines = file($lines, FILE_IGNORE_NEW_LINES);
may this help you... :)
you can check all line of text file with in_array("you want", $lines) as you desire...if its not dynamically....
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/