How to set each line of a text file as a variable? - php

I got a simple php script that is storing the content of POST in to a text file. data.txt looks like this:
Something - Line1
Something - Line2
Something - Line3
Something - Line4
I'm trying to figure out the best way to set each line as a variable e.g.
$line1 = "Something - Line1";
$line2 = "Something - Line2";
$line3 = "Something - Line3";
$line4 = "Something - Line4;"
so I can use it for further processing. Please note that the numbers of line can change. Any ideas? :-)
Thanks!

Best to use an array. Check out file():
$lines = file('/path/to/file.txt');
Then you access the lines starting from 0:
echo $lines[0];
echo $lines[1];
//etc...
Or loop through them:
foreach($lines as $line) {
echo $line;
}

This link provides your answer: Read each line of txt file to new array element
The link makes use of the while loop and searches for the end of the file
The link provided uses the following code:
<?php
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>

Related

str_split adding empty elements in array end when reading from file

I found interesting problem while I was trying to achieve something simple like splitting string into array. The only difference here is that Im trying to take the string from .txt file
My code is the following:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
This is the content of my .txt file
4
abc
abcba
abcd
cba
I tried with array_filter() and all other possible solutions/functions. Array filter and array diff are not removing the empty elements, no idea why... Also in my txt file there are no blank spaces or anything like that. Is this a bug in a str_split function ? Any logic behind this ?
The extra whitespace is a newline. Each row except the last technically contains all of the text contents you see, plus a newline.
You can easily get rid of it by e.g.
$string = rtrim(fgets($handle));
Also, fgets($fp); makes no sense since there's no variable $fp, should be fgets($handle); given your above code.
Trimming the spaces and need to change your fgets($fp) to fgets($handle) as there's no variable like of $fp.You need to update your code into as
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}

Read .txt table from PHP

I'm new in PHP. I'm trying to design a simple Glossary for Primary English Students.
I want to use a .txt as database, exploded by ":". I've got a txt like this:
Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión
By the moment I know how to print the whole text or one column, but can't print a single word:
<?php
$file = fopen("bank.txt", "r");
while(!feof($file)) {
echo fgets($file). "<br />";
}
fclose($file);
?>
How can I print only ONE SPECIFIC WORD?
e.g. What code is recquired to print only the second word of the third line?
Like mentioned in the comments... in the future you should inform yourself how to ask questions on SO.
Regarding your question, you should take a look at the explode-function and foreach-loops of PHP.
Example:
$data = 'Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión';
$arrData = array();
$lines = explode( "\n", $data );
foreach ($lines as $line) {
$words = explode( ":", $line );
$arrData[] = array( $words[0], $words[1] );
}
echo( $arrData[2][1] );
// Prints: "Coche"
This should work for you:
Just get your file into an array with file(). Then go through each line with array_map() and explode() the line by a : colon.
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map(function($v){
return explode(":", $v);
}, $lines);
print_r($lines); //echo $lines[0][1] <- Will print the first line, second word
?>
Or what you could also do, is change your file into a .ini file format, e.g.
Hola="Hello"
Good Bye="Adios"
Car="Coche"
Banana="Plátano"
Plane="Avión"
And then you can simply use parse_ini_file(), e.g.
<?php
$file = parse_ini_file("test.ini");
//^^^^ See also here the extension
print_r($file);
?>

textfile to an array...any ideas?

I am needing to turn a textfile into an array...I am not sure how to go about this because the other features ive seen for php take an entire file and put it into an array but not quite how I want it to be so I am looking for advice here..
The following is written in a textfile:
"jim kroi,richard wuu,yan kebler,justin persaud"
How can I use php to make an array where automatically a loop puts each name as an item of the array until all the names run out?
so the end result of what I am trying to do is:
$array= array("jim kroi","richard wuu","Yan kebler","justin persaud");
So a loop of some sort would basically search upto each comma and extract the name before it until all of the names run out....
There are some php substr and such functions but I cant quite think of how to do this..
Yes, I do have code, here it is:
<?php
error_reporting(-1);
$fp = fopen('numbers.csv', 'w');
fputcsv($fp, $_POST['names']);
fputcsv($fp, $_POST['numbers']);
fclose($fp);
?>
i put them all in a csv but now how can I make 2 arrays, one with name the other with numbers? http://imageshack.us/photo/my-images/215/csv.png/
using implode I get the error:
Warning: implode() [function.implode]: Bad arguments. in C:\Program Files\xampp\htdocs\xampp\something.php on line 14
<?php
error_reporting(-1);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
fclose($fh);
?>
Try to use fgetcsv with a custom separator.
Something like:
$names = array_map('trim', explode(',', file_get_contents('%yourFileHere')));
Use the explode() function.
$string = "jim kroi,richard wuu,yan kebler,justin persaud";
$arrNames = explode(',', $string);
var_dump($arrNames);
see explode, read the file with file_get_contents
You can try explode;
$names = explode(',', $line);
http://php.net/manual/en/function.explode.php
it's simple
<?PHP
$myFile = "testFile.txt"; // file path and name
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
?>

How to read line by line in php

when i try to insert each line into my oracle database i get an error stating invalid number, but if have only one line in the file it works fine.
$file = #fopen('file.text', "r") ;
// while there is another line to read in the file
while (!feof($file))
{
// Get the current line that the file is reading
$currentLine = fgets($file) ;
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
}
fclose($file) ;
the lines look like this
1 4 100
1 4 101
Try this:
$currentLine = trim(fgets($file));
It's possibly failing on the newline/carriage-return at the end of the line.
If not, where is this insert() function defined? Build a debug section that echos or writes out the attempted queries so you can really see the issue.
Your explode() call is using 9 spaces as a separator, but your file only appears to have 5 spaces between each number. This means your $currentline be a single element array containing the original line, and not separate elements with a number in each.
Either change the number of spaces in the explode call, or change to
$currentLine = preg_split('/\s+/', $currentLine);
which will split on any number of sequential spaces.
I would double check that there is not a new line at the end of the file. Maybe even double check inside of php that the line read is not blank.
$lineCount=0;
// while there is another line to read in the file
while (!feof($file))
{
$lineCount++;
// Get the current line that the file is reading
$currentLine = fgets($file);
if(trim($currentLine) != ''){
$currentLine = explode(' ',$currentLine) ;
insert($currentLine) ;
echo "Inserted line number $lineCount<br />";
} else {
echo "There was a blank line at line number $lineCount.<br />";
}
}
$lines = explode("\n", str_replace("\r", "", file_get_contents("file.text")));
foreach ($lines as $line)
{
insert(explode(' ', $line);
}
try this :
// Read all data in the file
$file_all = file_get_contents('file.text') or die("unable to open file");
// create an array with each index = a line
$file_lines = explode(chr(13),$file_all);
// Insert each line found
foreach ($file_lines as $file_line) { insert($file_line); };

How do I read a text file into array of lines and display it using PHP?

I have text file that looks like this:
1 1 1 1
1 2 3 5
4 4 5 5
I want to read this text file into array of lines and display it. Can anyone help me do this?
This should get you going: php function file
<?php
$cont = file_get_contents("data.txt");
$lines = explode("\n",$cont); // $lines is now an array containing each line
// do something with data here
?>
make sure you use the correct line endings however as Windows uses \r\n and UNIX uses \n.
you can use fopen(), fgets(). see here
eg
$f=fopen("file","r");
if($f){
while (!feof($f)) {
$line = fgets($f, 4096);
print $line;
}
fclose($f);
}
You'd want to do something like this:
<?
$filename = "somefile.txt";
$arr = file($filename);
foreach($arr as $line){
print $line . "<br />";
}
?>
This one is working for me.
$array = explode("\n", file_get_contents('file.txt'));

Categories