Php split text by line and get specific element - php

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

Related

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

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

php retrieve data from text file

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

PHP Parse File, replacing not required items going wrong

I'm trying to parse each IP line from the following file (loading from the web) and I'm going to store the values in database so i'm looking to put them in to an array.
The file its loading has the following source:
12174 in store for taking<hr>221.223.89.99:8909
<br>123.116.123.71:8909
<br>221.10.162.40:8909
<br>222.135.5.38:8909
<br>120.87.121.122:8909
<br>118.77.254.242:8909
<br>218.6.19.14:8909
<br>113.64.124.85:8909
<br>123.118.243.239:8909
<br>124.205.154.181:8909
<br>124.117.13.116:8909
<br>183.7.223.212:8909
<br>112.239.205.245:8909
<br>118.116.235.156:8909
<br>27.16.28.174:8909
<br>222.221.142.59:8909
<br>114.86.40.251:8909
<br>111.225.105.142:8909
<br>115.56.86.62:8909
<br>59.51.108.142:8909
<br>222.219.39.194:8909
<br>114.244.252.246:8909
<br>202.194.148.41:8909
<br>113.94.174.239:8909
<br><hr>total£º 24¡£
So I guess I'm looking to take everything between the <hr>'s and add each line line by line.
However doing the following doesn't seem to be working (in terms of stripping it the parts i dont' want)
<?php
$fileurl = "**MASKED**";
$lines = file($fileurl);
foreach ($lines as $line_num => $line) {
$line2 = strstr($line, 'taking', 'true');
$line3 = str_replace($line2, '', $line);
print_r($line3);
}
?>
If you want to add the values to an array, why not doing that directly inside the loop? I'd do something like this:
$output = array();
foreach ($lines as $line) {
if(preg_match("/<br>\d/", $line)) {
$output[] = substr($line, 4);
}
}
print_r($output);
Look into PHP function explode: http://www.php.net/manual/en/function.explode.php
It can take a string, and create an array out of it, by splitting at a specific character. In your case, this might be <br>
Also, trim function can get rid of the whitespace when needed.

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