Read each line of a text file to a new array element - php

I want to enter each line of this text file in to a new array element, and i need the array to end up like so: Array ( [testuser] => 'testpassword' ) by using this text in the text file: 'testuser' => 'testpass'
The code i have now:
$filename = "logininfo.txt";
$fp = #fopen($filename, 'r');
if ($fp) { $LOGIN_INFORMATION = explode("\n", fread($fp, filesize($filename))); }

Use PHP's file function:
$array = file('logininfo.txt');
To ignore newlines and empty lines, provide the appropriate flags:
$array = file('logininfo.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
A good way to solve this, is PHP's parse_ini_file function.
Your file will have to look slightly different though, but I assume that is not a problem:
; file contents:
testuser = testpass
And in your PHP file:
$array = parse_ini_file('logininfo.txt', FALSE);

Assuming your file is like this :
user : blah
password : somthing
you could do it like this
$arr = array();
$filename = "test.txt";
$fp = fopen( $filename, "r" );
while ( ! feof( $fp ) ) {
$line = fgets( $fp, 1024 );
$temp = explode(":", $line);
$arr[trim($temp[0])] = trim($temp[1]);
}

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-writing problems

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>
And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));
Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>
It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.
$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.
You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

PHP read command output and process in array

I have following working code which read file contain and put into array but now i want to run command and place its output in array for example ls command
<?php
$path = "file.txt";
$file = fopen($path, 'r');
$data = fread($file, filesize($path));
fclose($file);
$lines = explode(" ",$data);
echo "<p><h1>$lines[0]</h1></p>";
?>
How do i read command output and place in array?
You can use shell_exec:
<pre><?php
$output = shell_exec('ls');
print_r($output);
My Preferred method would be to use popen. I would be trivial to put the results in an array
$fp = popen ("ls -l", "r");
$array = array();
while ($rec = fgets($fp)){
$array[] = trim($rec);
}
// do something cool with array

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/

Write to specific line in 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.

Categories