take special lines from txt database PHP - php

I have text database
0,Apple,Green
1,Banana,Yellow
2,Cherry,Red
and when I call getdata.php?row=2 I need get data which is 2,cherry,red
I am a bachelor in PHP and I have only one example ,
please help me for this problem.
thanks
$file_handle = fopen("./news.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
print $parts[0] . $parts[1] . $parts[2];
}
fclose($file_handle);

This would work and would also stop reading as soon as it found the right line (unlike the other answers who read the whole no file matter what)
if (isset($_GET['row']))
{
$file_handle = fopen("./news.txt", "rb");
$i = 0;
while (!feof($file_handle))
{
if ($i == $_GET['row'])
{
$line_of_text = fgets($file_handle);
$parts = explode(',', $line_of_text);
print $parts[0] . $parts[1] . $parts[2];
break;
}
$i++;
}
fclose($file_handle);
}

You first have to explode by rule with explode("/n", $txt) than you've an array of each rule. After you stored this explode in to a variable than you should explode a specific value again by ,.

A straightforward way to do this: if record number 2 is always on line number 3.
if (!isset($_GET['row']) || !is_int($_GET['row'])) {
echo "please supply a row number";
die;
}
$lines = file('news.txt');
// assumes record number 2 is on line 3
$row = $_GET['row'] + 1;
$parts = explode(',', $lines[$row]);
print $parts[0] . $parts[1] . $parts[2];
If record number 2 is not guaranteed to be on line 3
$row = $_GET['row'];
foreach ($lines as $line) {
if (strpos($line, $row) === 0) {
$parts = explode(',', $lines[$row]);
print $parts[0] . $parts[1] . $parts[2];
break;
}
}
If the file is extremely large you will want to read line by line from a buffer.
$row = $_GET['row'];
if ($fp = fopen('news.txt', 'r')) {
while ($line = fgets($fp)) {
if (strpos($line, $row) === 0) {
$parts = explode(',', $line);
print $parts[0] . $parts[1] . $parts[2];
break;
}
}
fclose($fp);
}

Related

fopen is duplicating the same line

I have a file that looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567
I made a function that when executed adds a given number or removes it if already present, which is $added and equals 100 for this example. This is my code:
$added = $_GET['added']; //100 for this example
$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
foreach ($details as $key => $value) {
if ($key == 5) {
$newline .= str_replace("[" . $added . "]", "", $value);
} else {
$newline .= $value . "||";
}
}
$line = $newline . "\n";
}
fputs($f, $line);
}
fclose($f);
}
this code is supposed to remove the [100] from the Rocky line since its already present which it kinda does. However, upon further execution instead of adding it back it duplicates the Rocky line and messes it up so the file looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567
3||Rocky||21||male||USA||[100][200]55.183.567
||
||
why is it doing this? I cant make any sense out of it...
Thank you.
First, you should read the file before you open it for output, because opening with the w mode truncates the file.
Second, you don't need to loop over the fields in $details if you just want to change one of them. Just access and assign it by index.
Then you can put the line back together with implode().
$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
if (strpos("[$added]", $details[5]) === false) {
$details[5] = "[$added]" . $details[5];
} else {
$details[5] = str_replace("[$added]", "", $details[5]);
}
$line = implode('||', $details)
}
fputs($f, $line);
}
fclose($f);

php how to get whole line after spicific character from text file?

I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.

Find string in file and display lines number

I'm new at PHP so I'm need help to build this script.
I have a file.txt file with following lines:
aaaa 1234
bbba 1234
aaaa 1236
cccc 1234
aaaa 1238
dddd 1234
I want to find the line with string "aaaa" and print:
String "aaaa" found 3 times at lines: 1, 3, 5.
And better it can print these lines.
I tried this code:
<?
function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
$line_number = '';
if ($file_handler = fopen($filename, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search); //convert file and search string
$line = strtolower($line); //to lowercase
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number .= $i.",";
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or filename";
}
//if no match found
if(count($line_number)){
return substr($line_number, 0, -1);
}else{
return "No match found";
}
}
$output = find_line_number_by_string('file.txt', 'aaaa');
print "String(s) found in ".$output;
?>
But I dont know how to count total of strings found (3) and print each found line.
Thank in advance.
There are lots of ways to do this that produce the same final result but differ in the specifics.
Assuming that your input is not large enough that you are concerned about loading it in memory all at once, one of the most convenient approaches is to use file to read the file's contents into an array of lines, then preg_grep to filter the array and only keep the matching lines. The resulting array's keys will be line numbers and the values will be whole lines that matched, perfectly fitting your requirements.
Example:
$lines = file('file.txt');
$matches = preg_grep('/aaaa/', $lines);
echo count($matches)." matches found.\n";
foreach ($matches as $line => $contents) {
echo "Line ".($line + 1).": ".$contents."\n";
}
$str = "aaaa";
$handle = fopen("your_file.txt", "r");
if ($handle) {
echo "String '".$str."' found at lines : ";
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
echo implode(", ", $arr_lines).".";
}
UPDATE 2 :
$file = "your_file.txt";
$str = "aaaa;";
$arr = count_line_no($file, $str);
if(count($arr)>0)
{
echo "String '".$str."' found at lines : ".implode(", ", $arr).".";;
}
else
{
echo "String '".$str."' not found in file ";
}
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen("your_file.txt", "r");
if ($handle) {
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
}
return $arr_lines;
}
**Try it for solve your problam **
if(file_exists("file.txt")) // check file is exists
{
$f = fopen("file.txt", "r");
// Read line by line until end of file
$row_count = 0;
while(!feof($f))
{
$row_count += 1;
$row_data = fgets($f);
$findme = 'aaaa';
$pos = strpos($row_data, $findme);
if ($pos !== false)
{
echo "The string '$findme' was found in the string '$row_data'";
echo "<br> and line number is".$row_data;
}
else
{
echo "The string '$findme' was not found ";
}
}
fclose($f);
}

How to get a recuring parts from a file in php

I have a file file.txt. This file has portions and parts that recur throughout the file. I
am trying to read the parts between the last and the first key words.
I have managed to get the first and the last key words but I can't read the lines between the key words.
Here is my script
$file=file('file.txt');
$begin = 'first_line';
$end='last_line';
foreach ($file as $lineNumber => $line) {
$lineNumber++;
if (strpos($line,$begin))
{
echo $lineNumber.$line."<br/>";
}
elseif (strpos($line,$end))
{
echo $value."<br/>";
}
echo $lineNumber. $line."<br/>";
}
Please some one assist me.
Here you go:
$lines=file('data.txt');
$begin = 'first_line';
$end='last_line';
$switch = false;
$content = "";
foreach ($lines as $line_num => $line) {
if(strpos($line, $begin) !== false) {$switch = true;continue;}
if(strpos($line, $end) !== false) $switch = false;
if(!$switch) continue;
$content .= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
echo $content;
This will do it:
$file = file('file.txt');
$begin = 'first_line';
$end = 'last_line';
$isInside = false;
foreach ($file as $lineNumber => $line)
{
$lineNumber++;
if (!(strpos($line,$begin)===false))
$isInside = true;
if ($isInside)
echo $lineNumber." : ".$line."<br/>";
if (!(strpos($line,$end)===false))
$isInside = false;
}
Some points:
You were displaying everything regardless, my script only shows lines between $begin and $end.
Your comparison is case-sensitive
You had a major bug using strpos and assuming it returns true if it matches. It could also return 0 if the string matches at the beginning,hence using === to catch this. See the disclaimer on the strpos page.
$file=fopen("welcome.txt","r");
while(!feof($file))
{
$open=fgets($file);
print $open;
}
fclose($file);

PHP - parsing a txt file

I have a .txt file that has the following details:
ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg
What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.
Thanks
You can do that easily this way
$txt_file = file_get_contents('path/to/file.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode('^', $data);
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
$info[$row]['images'] = $row_data[3];
//display data
echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
echo 'Row ' . $row . ' IMAGES:<br />';
//display images
$row_images = explode(',', $info[$row]['images']);
foreach($row_images as $row_image)
{
echo ' - ' . $row_image . '<br />';
}
echo '<br />';
}
First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.
After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.
If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);
Use explode() or fgetcsv():
$values = explode('^', $string);
Or, if you want something nicer:
$data = array();
$firstLine = true;
foreach(explode("\n", $string) as $line) {
if($firstLine) { $firstLine = false; continue; } // skip first line
$row = explode('^', $line);
$data[] = array(
'id' => (int)$row[0],
'name' => $row[1],
'description' => $row[2],
'images' => explode(',', $row[3])
);
}
By far the best and simplest example of this I have come accross is quite simply the file() method.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
This will display all the lines in the file, this is also applicable for a remote URL.
Simple and clear.
REF : IBM PHP Parse
I would like to contribute a file that provides atomic data structures.
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);
Try fgetcsv() with ^ as the separator character:
$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);
http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...
$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
$details[] = $line;
}
fclose($fh);
youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:
list($number, $status, $text, $images) = explode("^", $data);
$splited_images= preg_split(',', $images);
My solution
function parseTextFile($file){
if( !$file = file_get_contents($file))
throw new Exception('No file was found!!');
$data = [];
$firstLine = true;
foreach(explode("\n", $file) as $line) {
if($firstLine) {
$keys=explode('^', $line);
$firstLine = false;
continue;
} // skip first line
$texts = explode('^', $line);
$data[] = array_combine($keys,$texts);
}
return $data;
}

Categories