php retrieve data from text file - php

Imagine I have a certain text file like this:
Welcome to the text file!
-------------------------
Description1: value1
Description2: value2
Description containing spaces: value containing spaces
Description3: value3
Storing this data into a text file would be easy, like this:
$file = 'data/preciousdata.txt';
// The new data to add to the file
$put = $somedescription .": ". $somevalue;
// Write the contents to the file,
file_put_contents($file, $put, FILE_APPEND | LOCK_EX);
With a different description and value every time I write to it.
Now I would like to read the data, so you would get the file:
$myFile = "data/preciousdata.txt";
$lines = file($myFile);//file in to an array
Lets say I just wrote "color: blue" and "taste: spicy" to my text file. I don't know on which lines they are, and I want to retrieve the value of the "color:" description.
Edit
Should I let php "search" though the file, return the number of the line that contains the "description", then put the line in a string and remove everything for the ":"?

With explode you can make an array containg the "description" as a key and the "value" as value.
$myFile = "data.txt";
$lines = file($myFile);//file in to an array
var_dump($lines);
unset($lines[0]);
unset($lines[1]); // we do not need these lines.
foreach($lines as $line)
{
$var = explode(':', $line, 2);
$arr[$var[0]] = $var[1];
}
print_r($arr);

I don't know how you want to use those values later on. You can load data into an associative array, where the descriptions are keys:
// iterate through array
foreach($lines as $row) {
// check if the format of this row is correct
if(preg_match('/^([^:]*): (.*)$/', $row, $matches)) {
// get matched data - key and value
$data[$matches[1]] = $matches[2];
}
}
var_dump($data);
Please note that this code allows you to fetch values with colons.
If you are not sure if the descriptions are unique you can store values as an array:
// iterate through array
foreach($lines as $row) {
// check if the format of this row is correct
if(preg_match('/^([^:]*): (.*)$/', $row, $matches)) {
// get matched data - key and value
$data[$matches[1]][] = $matches[2];
}
}
var_dump($data);
This prevents from overwriting data parsed earlier.

Since $lines is an array, you should loop it looking for the ":" and separating the line in two: description and value.
Then:
<?php
$variables = array();
unset($lines[0]); //Description line
unset($lines[1]); //-------
foreach ($lines as $line) {
$tempArray = explode( ": ", $line ); //Note the space after the ":", because
values are stored with this format.
$variables[$tempArray[0]] = $tempArray[1];
}
?>
There you have in variables an array, whose keys are the descriptions and values are your values.

You could use a regular expression to split the line and retrieve the parte after ":" or just yse the explodecommand which returns an array of the string split by every ":" such as:
foreach ($lines as $line_num => $line) {
$split_line = explode(":", $line);
// echo the sencond part of thr string after the first ":"
echo($split_line[1])
// also remove spaces arounfd your string
echo(trim($split_line[1]));
}

Related

How can I read contents of a text file using PHP & process elements?

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);

Php split text by line and get specific element

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

Read from file and create associative array?

I am able to read from a file and create an array however I get the following error: Notice: Undefined offset: 1. Within my array there is one element that is empty and I don't understand why it is empty.
My text file is in the following format:
#EXTINF:0,ABC family USA[]http://localhost/IpInfo/index.html
#EXTINF:0,CBC[]http://localhost/IpInfo/index1.html
#EXTINF:0,A&E[]http://localhost/IpInfo/index2.html
Here is my code:
$fh = fopen('file1.txt', 'r');
$theData = fread($fh, filesize('file1.txt'));
$arr = array();
$my_array = explode("\r\n", $theData);
foreach($my_array as $line){
$tmp = explode("[]", $line);
$arr[$tmp[0]] = $tmp[1];
}
fclose($fh);
echo '<pre>';
echo print_r($arr);
I'm not quite sure what the problem is? Any help would be much appreciated!
Thanks!
Probably your input data doesn't use \r\n as the line delimiter? I'm not sure whether I got the problem completely. Also you might want to take empty lines into account.
I would use the file() function, which simplifies to iterate over the lines of a file and can handle Windows and Unix line feeds and check for empty lines:
$arr = array();
foreach(file('a.txt') as $line){
// I'm using `trim()` here since $line
// will still contain the newline delimiter
$line = trim($line);
// Skip empty lines
if(empty($line) {
continue;
}
$tmp = explode("[]", $line);
$arr[$tmp[0]] = trim($tmp[1]);
}
echo '<pre>';
print_r($arr);
Output:
<pre>Array
(
[#EXTINF:0,ABC family USA] => http://localhost/IpInfo/index.html
[#EXTINF:0,CBC] => http://localhost/IpInfo/index1.html
[#EXTINF:0,A&E] => http://localhost/IpInfo/index2.html
)
The reason is that the explode function splits your read-in data at the "\r\n". And you have a new line after the last line, and that's what results in the last "array" with no keys or values. To fix this, replace this line : $my_array = explode("\r\n", $theData); with these:
$my_array = explode("\r\n", $theData);
array_pop($my_array);

Get contents from a text file and save its values

I need to get the contents of a text file called file.txt. The contents of that file are:
word1,word 2,word 3 1,another word 1,
I have a config.php which includes:
$file = "file.txt";
$value = explode(",", $file);
And script.php file which will execute other commands based on $value which includes:
if (count(explode($value, $chat))>1) {
After that, it will execute a command if the $value was detected in $chat. So, I need the $value to be a separate word in file.txt.
How can I do this?
If you're looking for more flexibility, you might want to try using preg_split rather than explode, which splits on a regular expression. For example, to split on newlines and commas, you could use this:
$text = file_get_contents('text.txt');
$values = preg_split('/[\n,]+/', $text);
Testing it out:
$s = "word1,word 2\n word 3";
print_r(preg_split('/[\n,]+/', $s));
Output:
Array
(
[0] => word1
[1] => word 2
[2] => word 3
)
Putting that into your script:
$file = "file.txt";
$text = file_get_contents($file);
$values = preg_split('/[\n,]+/', $text);
Then $values is an array, which you can loop over in the other script:
foreach ($values as $value) {
// do whatever you want with each value
echo $value;
}
Reading file contents:
file_get_contents
Explode string:
explode
Get file as array (each line => one item):
file
BTW: a short google would already answer your question...
In config.php add this code, be sure that the file is in the same folder
$value = file_get_contents('file.txt');
Then in script.php add this code:
$pieces = explode(",", $value);
Read more about file_get_contents and explode. (Click on the names)

How do I edit this text file using PHP?

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>';

Categories