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];
}
Related
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
}
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'm trying to display only the rows that contain a specific word in a specific column. Basically I would like to show only the rows that have "yes" in the Display column.
First_Name, Last_Name, Display
Kevin, Smith, yes
Jack, White, yes
Joe, Schmo, no
I've been trying various things with fgetcsv & str_getcsv from other answers and from php.net but nothing is working so far.
It doesn't do anything but this is my current code:
$csv = fopen('file.csv', 'r');
$array = fgetcsv($csv);
foreach ($array as $result) {
if ($array[2] == "yes") {
print ($result);
}
}
Let's have a look at the documentation for fgetcsv():
Gets line from file pointer and parse for CSV fields
fgetcsv reads a single line, not the whole file. You can keep reading lines until you reach the end of the file by putting it in a while loop, e.g.
<?php
$csv = fopen('file.csv', 'r');
// Keep looping as long as we get a new $row
while ($row = fgetcsv($csv)) {
if ($row[2] == "yes") {
// We can't just echo $row because it's an array
//
// Instead, let's join the fields with a comma
echo implode(',', $row);
echo "\n";
}
}
// Don't forget to close the file!
fclose($csv);
You should use data tables.
https://datatables.net/examples/basic_init/zero_configuration.html
That's how I deal with my textfiles. But be carefull, with a large amount of Data (> 10000 rows) you should have a loog at the deferRender option.
https://datatables.net/reference/option/deferRender <-- JSON DATA required.
still struggling with PHP and CSV file manipulation. I will try to ask this properly so I can get some help.
I have a CSV file with about 4000 lines/rows, and I wrote this code to create an array of the entire CSV, and pull the the LAST line of the CSV file out to use in my script. The code works to to all this wit success.
// CREATE ASSOCIATIVE ARRAY FROM LAST ROW OF CSV FILE
$csv = array();
if (FALSE !== $handle = fopen("Alabama-TEST.csv", "r"))
{
while (FALSE !== $row = fgetcsv($handle))
{
$csv[] = $row;
}
}
$new_csv = array();
foreach ($csv as $row)
{
$new_row = array();
for ($i = 0, $n = count($csv[0]); $i < $n; ++$i)
{
$new_row[$csv[0][$i]] = $row[$i];
}
$new_csv[] = $new_row;
}
The variable $new_row is the last row in the CSV and I am able to use the data fine. But when the script is finished running I want to delete this last row called $new_row.
Here is an example of my CSV file at the top view;
CITY ADDRESS STATE NAME
Birmingham 123 Park St. Alabama Franky
So I just want to remove the last row and keep the header at the top, for the next time the script runs. I've been trying for 3 days solid trying to figure this out, so I'm hoping some kind person who KNOWS WHAT THEY ARE DOING can help.
Here is the code I have tried to remove the last row;
$inp = file('Alabama-TEST.csv');
$out = fopen('Alabama-TEST.csv','w');
or ($i=0;$i<count($inp)-1;$i++)
fwrite($out,$inp[$i]);
fclose($out);
Since I'm using a large file at around 4000 rows, is there a way to do this without using too much memory?
You need to use array_pop on your array ($new_csv) and fputcsv to save the file:
array_pop($new_csv); // Removes the last element in the array
$out = fopen('Alabama-TEST-new.csv','w');
foreach ($new_csv as $row) { // sorry for writing it badly, try now
fputcsv($out, $row);
}
fclose($out);
I don't have an environment to test this, sorry.
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