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);
?>
Related
Currently I have a code, which displays data from a txt file, and randomizes it after converting it into an array.
$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);
I am trying to make it so that, after this random value is displayed.
$search = $array[$rand_keys[0]];
We're able to store this into another txt file such as completed.txt and remove the randomized segment from our previous txt file. Here's the approach I tried, and surely didn't work out with.
$a = 'test.txt';
$b = file_get_contents('test.txt');
$c = str_replace($search, '', $b);
file_put_contents($a, $c);
Then to restore into a secondary file, I was messing with something like this.
$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $search;
}
}
file_put_contents('completed.txt', $result);
This actually appears to work to some extent, however when I look at the file completed.txt all of the contents are EXACTLY the same, and there's a bunch of blank spaces being left behind within test.txt
There are some better ways of doing it (IMHO), but at the moment you are just removing the actual line without the new line character. You may also find it will replace other lines as it just replaces the text without any idea of content.
But you will probably fix your code with the addition of replacing the new line...
$c = str_replace($search."\n", '', $b);
An alternative way of doing it is...
$fileName = 'test.txt';
$fileComplete = "completed.csv";
// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));
// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);
I'm trying to read in a name from a text file in PHP and remove spaces in the names, which I do using preg_replace in a function.
function fixName($input) {
$input = preg_replace('/[^ \w-]/', ' ', $input);
return $input;
}
echo fixName('BOB VAN'), "\n";
However, I have a text file that has multiple names similar to the one above each on a new line, and I'm trying to figure out how to store those names that are read in from the file and process and output them. Would I do something such as reading the file and storing them into an array?
The text file looks like this
ID FIRST LAST
348 BOB VAN
349 ALBERT JOHN
If you want to read file string by string and store it in an array then you can try something like:
$output = array();
$handle = fopen("file.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle);
$buffer = preg_replace('/[^ \w-]/', ' ', $buffer);
list($id, $name) = explode(' ', $buffer, 2);
$output[$id] = $name; //you can index elements by ID or store ID and name as nested array
}
fclose($handle);
var_dump($output);
I have a big text file, split by new lines and on every line elements split by ';', like this:
1;1;20;3.6;0%;70%;25%;0%;5%;
1;2;80;4;45%;20%;20%;15%;0%;
1;3;80;4;40%;35%;5%;20%;0%;
1;4;20;3.6;15%;40%;38%;5%;2%;
1;5;20;3.6;30%;18%;33%;20%;0%;
1;6;80;4;27%;47%;23%;3%;0%;
What I would like to do is with PHP is to read the file correctly and access a specific element in any row, for example on row 2, element 3 (maybe, [1][2], if considered as indexes) and print it.
<?php
//split by new line
$text = fopen("public/data/data1.txt", "r");
if ($text) {
while (($lines = fgets($text)) !== false) {
//split by ;
$line = explode(';', $lines);
//access a specific element
}
fclose($text);
} else {
// error opening the file.
}
?>
Does somebody know how I could access this elements?
You can explode the string twice.
First on lines, then on ;.
$arr = explode(PHP_EOL, $str);
Foreach($arr as &$line){
$line = explode(";", $line);
}
https://3v4l.org/5fbvZ
Then echo $arr[1][2]; will work as you wanted
I do have a text file having around 400k data in it. and its content is like this..
1,james
2,mathew
3,yancy
4,brandon
5,molner
6,nick
7,neil...and so on
How do I remove numbers and comas from this text file and keep only names?
Read the file into an array, where each array item is one line. Walk throught the array, find the first comma, and remove it and everything before. Then write it all back out again.
// Warning! Brain-compiled code ahead.
$arr = file('myfile.txt');
foreach ( $arr as &$val )
$val = substr($val, strpos($val, ',') + 1);
file_put_contents('myoutfile.txt', implode(PHP_EOL, $arr));
Note - no error checking. If a line lacks a comma, or comma is the last character, chaos ensues.
400k isn't incredibly much, so you should get away with this (tested):
foreach (file($path) as $line)
print preg_replace("~^[0-9]+\,(.*)~", "$1", $line);
Here is a perl one liner that do the job:
perl -i.save -pe 's/^\d+,//' test.txt
The original file will be saved in test.txt.save
This is tested and will return it as a list but you can save it to a database if you want:
$file_path='my_file.txt';
$file_handler = fopen($file_path, 'rt');
$doc = fread($file_handler, filesize($file_path)+1);
$rows = explode("\n", $doc);
$rows_array = array();
foreach ($rows as $row) {
$data = explode(",", $row);
$return_array[] = $data[1];
}
//print_r($return_array);
//you can save it to a db
echo '<ul>';
foreach($return_array as $value){
echo '<li>'.$value.'</li>';
}
echo '</ul>';
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'));