Write to specific line in PHP - php

I'm writing some code and I need to write a number to a specific line. Here's what I have so far:
<?php
$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');
for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;
$line++;
echo $line;
I don't know where to continue after this. I need to write $line to that line, while maintaining all the other lines.

you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.
<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );

This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.
$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES); // read file into array
$line = $stats[$offset]; // read line
array_splice($stats, $offset, 0, $newline); // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats)); // write to file

I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:
<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
?>
Because these lines don't work since the arg of the array is not an index:
$line = $stats[$offset];
$lines[$line_i_am_looking_for] = 'my modified line';
Had to add that +1 to have the new line under the searched text.

Related

Associative-array in PHP from CSV / TXT file

I have a problem with associative-array in PHP – when the source of the arrays is from a text file.
When I write something as follows:
$logins = array('user1' => '1234','user2' => '2345','user3' => '3456');
It all works as expected.
So, I tried to call those arrays from CSV file like that:
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if (empty($line_of_text)) { break; }
$logins = array($line_of_text[0] . '=>' . $line_of_text[1]); /* remove the => and seperate the logins with "," on CSV */
}
It didn't work.
There are a lot close related questions and answers here on SO but I did read and try to implant them without no success. Please Guide me.
Edit: data.csv looks like as follows.
user1,1234;
user2,2345;
user3,3456;
You can avoid those loops, conditionals, and fopen()/fclose() messiness:
<?php
// read the file into an array
$arr = file("data.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// split each line at the comma
array_walk($arr, function(&$v, $k){$v=explode(",", $v);});
// build an array from the data
$keys = array_column($arr, 0);
$values = array_column($arr, 1);
$logins = array_combine($keys, $values);
Here is what I think you want
$logins = array();
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
// At this point, $line_of_text is an array, which will look
// something like this: {[0]=>'user1',[1]=>'1234'}
if (empty($line_of_text)) { break; }
$logins[$line_of_text[0]] = $line_of_text[1];
// So the line above is equivalent to something like
// $logins['user1'] = '1234';
}
This would probably also work, though I think it's not something you really want to get into
/* $dataFile = fopen("data.txt", "r"); */
$dataFile = file_get_contents("data.txt");
/* logins = array($dataFile); */
eval('$logins = ' . $dataFile . ';');

php file_put_content overwrite

So i found this code which lets be write to a specific line
function SetSiteName(){
global $session, $database, $form;
$filepathname = "include/classes/constants.php";
$target = 'sitename';
$newline = 'define("sitename", "Testing.");';
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +32;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
header("Location: ".$session->referrer);
}
however it will not overwrite whats on that line it'll go to the next line and put the data in.. I'd like to make it overwrite what currently is on that line?
Any thoughts?
You can overwrite a line of a file with this code.
$filename = "file.txt";
$content = file_get_contents($filename);
$lines_array = explode(PHP_EOL, $content);
//overwrite the line that you want.
$lines_array[5] = "New text at line 6!";
file_put_contents($filename, implode(PHP_EOL, $lines_array));

php set lines in a text file to an array value

Im looking to do something like the following
$file = ('file.txt');
$fopen($file);
then read each line from the file individually and set it as a specific array
like so
read $file get $line1 set as $array[0]
read $file get $line2 set as $array[1]
read $file get $line3 set as $array[2]
I would like to use these arrays created from the lines on the text file IN PLAIN TEXT like this:
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
$urlout2 = file_get_contents("http://myurl.com/?=$line2");
echo $urlout2;
$urlout3 = file_get_contents("http://myurl.com/?=$line3");
echo $urlout3;
So if the array were 123.22.11.22 the link would look like this:
$line1 = array[0] (123.22.11.22)
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
and the result would be
Info for 123.22.11.22
more info
some more
Modified answer as per the change indicated by the user :
Reading 2 lines on each loop..
$lines = file("file.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("http://myurl.com/?=".$lines[$i]);
echo file_get_contents("http://myurl.com/?=".$lines[($i + 1)]);
}
Imp Note : A URL can be used as a filename with file_get_contents() function, only if the fopen wrappers have been enabled.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo file_get_contents("http://myurl.com/?=$line");
}
fclose($handle);
}
The answer was to insert a "\n" separator upon inserting into the text file, then removing it after the first result was called
$lines = file("geo.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("https://test.com/api/GEO.php?info=".$lines[$i]);
$lolz = file_get_contents("https://test.com/api/GEO.php?info=".$lines[($i + 1)]);
$lolz = str_replace(" \n", '', $lolz);
echo "<br>".$lolz;
}

Write to file using SplFileObject()

I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?
Here is my code to get the line:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
How do I insert a string on that line?
Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.
This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

Categories