I have a list.txt file which I get its contents with fgets. I then echo the contents of each line in the list.txt file in a while loop until fgets reaches end of file. Now, I want to delete a line after it has been echoed in the lists.txt file after it has been echoed.
I've tried putting the lines in another file (list2.txt) and then using the ideas of put_contents but i've been unsuccessful in doing that and in a few other things i've thought of to try. I can't help but feel like i'm overthinking it.
$list = fopen("list.txt","r");
while(! feof($list))
{
try{
$lines = fgets($list);
echo "$lines \n";
// I don't need to delete the lines here
}
catch (Exception $e)
{
echo "Error \n ";
// I want to delete the lines here
exit;
}
}
fclose($list);
// I want to delete the lines here
I was able to finally do this using file() and for loop but couldn't with fgets and while loop. Barmar's comment above pointed me in the right direction but implode wasn't cutting it for me.
$list = file('list.txt'); // opens list.txt into an array
$listcount = count($list); // counts the number of lines/array elements
for ($x = 0; $x <= $listcount; $x++) //for loop to echo and delete each line
{
echo "\n $list[$x]\n";
unset($list[$x]); // deletes the lines that's just being echoed
file_put_contents("list.txt", $list); // puts the remaining contents of
//the array back into list.txt file
}
Related
I am trying to read data from a plain text file from an industrial machine recipe. The file is generated automatically by the tool. I want to access a specific parameter in a specific section of the file.
The parameter is called "LightSrcRef_NominalGL" The problem is that there are some number of parameters named as such in the file. I specifically want the first one, and only the one, that occurs after the tag "[Scan2d]"
Note that the parameter I need does not always show on the same line number and that [Scan2d] does not always show up in the same place, but I need the parameter in the Scan2d section. It also appears that the LightSrcRef_NominalGL parameter is not always the same number of lines after [Scan2d].
What I had hoped was to read the file line by line. When I get to [Scan2d], set a flag, then when I get to the parameter, set my variable, then get out.
This is not happening. Instead, it is taking the first LightSrcRef_NominalGL in the file.
We have similar recipe analyzers, but this is the first one with this unique recipe structure. I have looked for a way to read the file in differently, but none produce different results.
When I print the actual line, it shows that the text file is reading it line by line. I do not understand why it is not behaving as expected.
Here is example of text file. In this case it is at the end of the file. In others, there will be another section after. I had to add an extra carriage return in the text file because this was not displaying them as separate lines. They are being read in by lines because if I have it print $line, it shows exactly one line.
[Scan2d]
CameraTypeName=2D
FocusPosAboveChuck=-2.59084174217116
Mag=5
CameraName=HighMag
DifRingPos=2
Gamma=-1
LightSrcDif_ColorFilter=Gray
LightSrcDif_NominalGL=0
LightSrcRef_ColorFilter=Cyan
LightSrcRef_NominalGL=195.424629214628
$catcher = 0; //used to verify the parameter only in scan2d section
$lines = file($dir.$default_directory."/".$current_recipe_file);
foreach($lines as $line)
{ $line_count ++;
if(preg_match("/[Scan2d]\b/i", $line))
{
$catcher = $line_count; //used to only catch the parameter in the Scan2D section
}
if(preg_match("/\bLightSrcRef_NominalGL=\b/i", $line))
{
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
if ($catcher >0)
{print $line . " ". $catcher . "<br>";
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher= 0;
break;
}
}
}
It is taking the first LightSrcRef_NominalGL in the file, not the one after Scan2d.
If the tags you are looking for are at the start of the lines in the file this can be made even simpler. I changed what you had slightly so that when the section you are interested in is found the foreach goes to the next record.
$catcher = 0;
foreach($lines as $line) {
if(preg_match("/[Scan2d]\b/i", $line)) {
$catcher = 1;
continue;
}
if(preg_match("/\bLightSrcRef_NominalGL=\b/i", $line)) {
if (!$catcher) {
continue; // we haven't found the right section yet
}
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
print $line . " ". $catcher . "<br>";
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher= 0;
break;
}
}
$lines = file($dir.$default_directory."/".$current_recipe_file);
$catcher = 0; //used to verify the parameter only in scan2d section
foreach($lines as $line)
{
if(preg_match("/\[Scan2d]/", $line))
{
$catcher = 1; //used to only catch the parameter in the Scan2D section
}
if (!$catcher)
{
continue; // haven't found the right one yet, skip the rest
}
else
{
if(preg_match("/LightSrcRef_NominalGL=/", $line))
{
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher = 0;
continue;
}
}
}
This worked, but many thanks to Dave who certainly put me on the right track!! The use of Else worked when I still do not fully understand why the second preg_match was executing if $catcher was not set (and it wasn't, I printed it to be sure).
The sample your provided seems to be a file in ini format. If this is really the case, there is a very simple solution using the parse_ini_file function
<?php
$values = parse_ini_file('sample.txt', true, INI_SCANNER_TYPED);
echo "The value is " . $values["Scan2d"]["LightSrcRef_NominalGL"] . "\n";
I tried against this sample.txt file
[test]
LightSrcRef_NominalGL=0
[Scan2d]
CameraTypeName=2D
FocusPosAboveChuck=-2.59084174217116
Mag=5
CameraName=HighMag
DifRingPos=2
Gamma=-1
LightSrcDif_ColorFilter=Gray
LightSrcDif_NominalGL=0
LightSrcRef_ColorFilter=Cyan
LightSrcRef_NominalGL=195.424629214628
[test2]
LightSrcRef_NominalGL=1
And the result is:
The value is 195.42462921463
Of course, this will work only if your entire file respects the ini format as in your sample data.
What I need to do is to be able to move the first row from a testdata.csv every time I run the .php to another .csv with the name testdata_new.csv(appending data).
This is an example of data that includes Name, Age, Job
Example data testdata.csv:
John,32,Scientist
Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics
This is what the .php will do running it:
Cut the first row from testdata.csv(john,32,scientist) and paste it to the new testdata_new.csv under the first row(header) that will always be "Name Age Job".
Save testdata_new.csv and testdata.csv with the remaining rows.
I did some tests but I'm still far away from the solution.
<?php
$file = "testdata.csv";
$f = fopen($file, "r");
$i = 0;
$file2 = str_replace(".csv", "_new.csv", $file);
$f2 = fopen($file2,"a");
while ($i<2) {
$record = fgetcsv($f);
foreach($record as $field) {
echo $field . "<br>";
}
$i++;
}
fwrite($f2,fread($f, filesize($file)));
fclose($f);
fclose($f2);
?>
Executing the script will display the first row of the template.csv file
and will produce another file with the name template_new.csv with the following rows:
Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics
What I really need to have in the template_new.csv file is only the first row displayed:
John,32,Scientist
And save again the template.csv without the first row as the idea is to cut and paste the rows, as following:
Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics
Thank you all in advance for your help!
As easy as this ;-)
$old_file = 'testdata.csv';
$new_file = 'testdata_new.csv';
$file_to_read = file_get_contents($old_file); // Reading entire file
$lines_to_read = explode("\n", $file_to_read); // Creating array of lines
if ( $lines_to_read == '' ) die('EOF'); // No data
$line_to_append = array_shift( $lines_to_read ); // Extracting first line
$file_to_append = file_get_contents($new_file); // Reading entire file
if ( substr($file_to_append, -1, 1) != "\n" ) $file_to_append.="\n"; // If new file doesn't ends in new line I add it
// Writing files
file_put_contents($new_file, $file_to_append . $line_to_append . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));
I am developing a log file viewer in php that should read 10 lines from the file (say 2 GB ) and when user clicks next then the consequent 10 lines has to be read.
when back button is pressed the last 10 lines has to be printed.
As of now I have implemented file read using fgets (due to size of file) and I trying to figure out how to seek the next 10 and previous 10 lines.
if($handle)
{
$cnt=1;
while(($buffer=fgets($handle))!==false and $cnt<=10) {
echo $buffer;
$cnt++;
}
if(feof($handle)) {
echo "error";
}
}
The SplFileObject class in PHP does what you want to do. See:
http://php.net/manual/en/splfileobject.seek.php
Example code:
<?php
// Set $lineNumber to the line that you want to start at
// Remember that the first line in the file is line 0
$lineNumber = 43;
// This sets how many lines you want to grab
$lineCount = 10;
// Open the file
$file = new SplFileObject("logfile.log");
// This seeks to the line that you want to start at
$file->seek($lineNumber);
for($currentLine=0; $currentLine < $lineCount; $currentLine++) {
echo $file->current();
$file->next();
}
?>
I have a php file that reads in information from a txt file and prints it on the screen into lines such as
1st line [ x ]2nd line[ x ]
etc etc etc
i am trying to add checkboxes next to all the lines of information, i managed to do a for loop that creates checkboxes depening on how many lines are read.
Now the final thing which i am stuck on is that i want the user to be able to click on any checkboxes and then click the submit button which should print out the chosen information on a new php file.
If the user ticked 1st line and submitted then it should display the text string "1st line" on the opening php file
I done some research and managed to use isset method to find out if it was checked, that worked but im still unsure how to read the information that was checked onto a new php file any help would be appreciated thank you
$filename = "file.txt";
$filepointer = fopen($filename, "r"); //open for read
$myarray = file ($filename);
// get number of elements in array with count
for ($counts = 0; $counts < count($myarray); $counts++)
{ //one line at a time
$aline = $myarray[$counts];
//$par = array();
$par = getvalue($aline);
if ($par[1] <= 200)
{
print "<input type=checkbox name='test'/>"." ".$par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]." ";
}
}
I think you are probably wanting to create an array which identifies which lines were checked? Well, you'll want to use an array to name your checkbox inputs. You can do this with a very similar syntax to PHP, by appending [] to the input name. For this specific case, you'll also want to explicitly index the array keys, which you can do like [index]. It will be easier to demonstrate this in code:
file1.php (FIXED):
<?php
$filename = "file.txt";
// file() does not need a file pointer
//$filepointer = fopen($filename, "r"); //open for read
$myarray = file($filename);
print "<form action='file2.php' method='post'>\n";
// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {
$count++; // increment the counter
$par = getvalue($line);
if ($par[1] <= 200) {
// Note the [] after the input name
print "<input type='checkbox' name='test[$count]' /> ";
print $par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]."<br />\n";
}
}
print "</form>";
file2.php:
<?php
foreach ($_POST['test'] as $lineno) {
print "Line $lineno was checked<br />\n";
}
EDIT
Say you wanted file2.php to display the lines from the file that were checked:
<?php
$filename = "file.txt";
$myarray = file($filename);
foreach ($_POST['test'] as $lineno) {
// We need to subtract 1 because arrays are indexed from 0 in PHP
print $myarray[$lineno - 1];
}
So I have a php script, I want to read in a file line by line, each line only contains one id. I want to select using sql for each id in the file, then print the result for each selection in the same file.
so far i have:
while (!feof($file))
{
// Get the current line that the file is reading
$currentLine = fgets($file) ;
//explodes integers by amount of sequential spaces
//$currentLine = preg_split('/[\s,]+/', $currentLine);
echo $currentLine; //this echo statement prints each line correctly
selectQuery($currentLine) ;
}
fclose($file) ;
as a test so far i only have
function selectQuery($currentLine){
echo $currentLine; //this is undefined?
}
The result of fgets is never undefined. However, your approach is way too low-level. Use file and array_filter:
$results = array_filter(file('input.filename'), function(line) {
return strpos($line, '4') !== false; // Add filter here
});
var_export($results); // Do something with the results here