Reading text file and checkboxes - PHP - php

Basically the code below reads in a text file and diplays it on the screen with checkboxes near each line. But now I want the user to be able to check any box and then display the selected results in a new PHP file - I thought I would have to read in the text file again and somehow refer it to the array, but I'm still stuck, so any help would be appreciated.
Thank you.
First php file
<?php
$filename = "file.txt";
$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>";
Second php file which should display the selected results
<?php
$filename = "file.txt";
$myarray = file($filename);
?>

I think you're over complicating the problem. You can just give the checkboxes a value atribute and read the array from the second page. Start with kus print_r ($_POST) on the second page to help you see what you have to work with.

1) Think of format of your text file (could be something like "Name1-Value 1-true\nName1-Value2-false")
2) Learn this function
3) Create a file with the default options
4) Make a PHP script that opens the file, makes an array and prints the resoult - for example:
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
$handle = null; //Similar to unset($handle);
$array = explode($fileString, "\n");
echo '<form action="./script2.php">';
foreach ($array as $value) {
$value = explode($value, "-");
echo '<input type="checkbox" name="'.$value[1].'" value="'.$value[2].'" checked="';
if ($value[3]==true) {
echo 'checked" /><br />';
} else {
echo '" /><br />';
}
}
5) Make the second script that edits the file - for example:
if ($_GET == null;) {exit("He's dead, Jim!");}
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
//Do something with the string :D
$handle = fopen('./file.txt','w');
fwrite($handle,$fileString);

Related

Generating a list from a text file in PHP

I am attempting to create an ordered list from a text file. As my code currently stands, it modifys the original text file with the input all on the same line(list number). e.g if I input "mercury" it will come out as 1. mercury, but if I input "venus", it will appear as 1.mercuryvenus
I am trying to get it to work so that if I input some text such as "mercury" and hit the submit button, it will appear as
1. mercury. If I input some more text such as "venus", it will appear as 2. venus, all in ordered list format. I assume that explode may be used for this, but I am unsure of how to implement this properly. Another option would be to create a new text file for each input if that were to be more efficient.
echo "<form method='post'>
<label>Enter some text</label><br>
<textarea name='textbox' cols='60' rows='5' required></textarea>
<br>
<input type='submit' name='submit' value='Submit'/>
<input type='hidden' name='step' value=''/>
</form>";
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = ("text.txt");
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a");
fwrite($file,$extract);
fread($file,filesize("text.txt"));
fclose($file); #Not sure where this should really go
$c = array(file_get_contents('text.txt'));
$x = explode(" ",$c); #Could be wrong format
echo "<ol>";
foreach($c as $r) {
echo "<li>" . $r. "</li>", "<br>";
}
echo "</ol>";
echo "</section>";
Here is the solution
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = "text.txt";
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a+");
fwrite($file," ".$extract);
#fread($file,filesize("$text"));
$x = explode(" ",file_get_contents($text));
if(isset($_POST['submit'])) {
echo "<ol>";
foreach ($x as $r) {
echo "<li>" . $r . "</li>", "<br>";
}
echo "</ol>";
echo "</section>"
First, the "a" in fopen($text,"a") means append. Which means if you already have the text "mercury" in your file and your run your program again with "venus", you will be appending "venus" on the end of "mercury" to get "mercuryvenus". If you want a space between the two, you will have to add it when your write it to file: fwrite($file, " ".$extract);
Second, you do $x = explode(... and then do not use $x in your foreach statement. Use $x instead of $c in your foreach.

array to xml or xspf make xspf file for embed vlc lugin playlist

i am trying input check box list current folder .mp3 get using gob function glob_grace list the audio files using check box then
get array check box values make xspf file using php
i write code all for array to xml
but small error please anyone tell me what error and the error where occurred !
<?php
foreach (glob("*.{mp3,mp4}", GLOB_BRACE) as $filename) {
$values = $filename ;
echo "<form action='p.php' method='POST'>";
echo "<input type='checkbox' name='foo[]' value='$values'>$values <hr>";
}
echo "<input type='submit' name='submit' value='Submit'>";
echo "</form>";
?>
it will go to next page below
<?php
$g = $_POST['foo'];
$cnt = count($g);
//function definition to convert array to xml
function array_to_xml($array, &$xml_user_info) {
for ($i=0 ; $i < $cnt ;$i++)
{
$track = $xml_user_info->addChild('track');
$track->addChild("location",$array[$i]);
}
}
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><trackList></trackList>");
//function call to convert array to xml
array_to_xml($g,$xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xspf');
//success and error message based on xml creation
if($xml_file){
echo 'XML file have been generated successfully.';
}else{
echo 'XML file generation error.';
}
?>
please give me answer solution working code
thanks in advance
If glob("*.{mp3,mp4}", GLOB_BRACE) returns an array with more than 1 item, you are generating the <form action='p.php' method='POST'> tag multiple times.
Maybe you could move the form declaration to outside of the foreach.
If I submit the form and I load the p.php, I get this Notice:
Notice: Undefined variable: cnt
You are using $cnt = count($g); to count the items, but you could also pass this $g and count its items inside the function array_to_xml.
I think that if you want to get the value from $_POST['foo'], you should first check if it is a POST and then check if the $_POST['foo'] is set.
Maybe this setup can help you:
<?php
//function definition to convert array to xml
function array_to_xml($array, &$xml_user_info)
{
for ($i = 0; $i < count($array); $i++) {
$track = $xml_user_info->addChild('track');
$track->addChild("location", $array[$i]);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['foo'])) {
$g = $_POST['foo'];
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><trackList></trackList>");
//function call to convert array to xml
array_to_xml($g, $xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xspf');
//success and error message based on xml creation
if ($xml_file) {
echo 'XML file have been generated successfully.';
} else {
echo 'XML file generation error.';
}
}
}
?>
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><playlist></playlist>');
$trackList = $xml->addChild('trackList');
foreach ($_POST['files'] as $video) {
$track = $trackList->addChild('track');
$track->addChild('location', 'file://'.$tmp_dir.'/'.$video['path']);
$track->addChild('title', $video['name']);
}
file_put_contents('playlist.xspf',$xml->asXML());

annoying array tags.. want a pretty output

What i'm trying to do is make my output usable for a spreadsheet.
I want each item in the output without array tags or not mashed together but starting with an asterisk and ending with a % sign.
<?php
$file = file_get_contents('aaa.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
//write to file. If file don't exist. Create it
file_put_contents('no_duplicates.txt',$no_duplicates);
?>
Maybe this would give you what you want:
$str = "*" . implode("% *", $no_duplicates) . "%";
echo '<pre>';
echo $str;
echo '</pre>';

PHP foreach loop read files, create array and print file name

Could someone help me with this?
I have a folder with some files (without extention)
/module/mail/templates
With these files:
test
test2
I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).
But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.
This is how I try to achieve this, without luck:
foreach (glob("module/mail/templates/*") as $templateName)
{
$i++;
$content = file_get_contents($templateName, r); // This is not working
echo "<p>" . $content . "</p>"; // this is not working
$tpl = str_replace('module/mail/templates/', '', $templatName);
$tplarray = array($tpl => $content); // not working
echo "<option id=\"".$i."\">". $tpl . "</option>";
print_r($tplarray);//not working
}
This code worked for me:
<?php
$tplarray = array();
$i = 0;
echo '<select>';
foreach(glob('module/mail/templates/*') as $templateName) {
$content = file_get_contents($templateName);
if ($content !== false) {
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
} else {
trigger_error("Cannot read $templateName");
}
$i++;
}
echo '</select>';
print_r($tplarray);
?>
Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.
The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.
Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.
You have a typo where you are referring to $templatName rather than $templateName.
$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
$i++;
$content = file_get_contents($templateName);
if ($content !== FALSE) {
echo "<p>" . $content . "</p>";
} else {
trigger_error("file_get_contents() failed for file $templateName");
}
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);

Adding/Incrementing data from a text file

I have a php file that contains some data when checked displays the checked data. How do I increment the variable "$visit" every time it is visited and save it to the text file?
new.php
<html>
<body bgcolor="#99FF00">
<table border="1">
<FORM ACTION="new.php" METHOD="POST">
Enter maximum price <input type="text" name="maximumprice"/>
<p><input type="submit" value="Go" name="Go"/>
</form>
<?
$mPrice = $_POST['maximumprice'];
$file1 = "properties.txt";
$filedata = fopen ($file1, "r");
$array1 = file ($file1);
print "<form action=\"visit.php\" method=\"POST\">";
for ($counter1 = 0; $counter1 < count($array1); $counter1++)
{
$arrLine = $array1[$counter1];
$pCode = getvalue ($arrLine, 0);
$price = getvalue ($arrLine, 1);
$picture = getvalue ($arrLine, 2);
$visit = getvalue ($arrLine, 3);
if ($price < $mPrice)
{
print "<tr>";
print "<td>";
print $pCode. "<br>";
print $price. "<br>";
//print $picture. "<br>";
print $visit. "<br>";
print "<input type=\"checkbox\" name=\"box[]\" value=\"$arrLine\" />";
print "</td>";
print "<td>";
printf("<img src='$picture' width='200' height='150'>");
print "</td>";
print "</tr>";
}
}
print '<input type="submit" name="Visit" value="Visit"/>';
// Move the form outside the for loop
print "</form>";
fclose ($filedata);
function getvalue ($text, $arrNo)
{
$intoarray = explode (",", $text);
return $intoarray[$arrNo];
}
?>
</table>
</body>
</html>
this is the second page, display.php
<html>
<body bgcolor="#99FF00">
<?
foreach ($_POST['box'] as $values)
{
echo "$values <hr/>";
}
?>
</body>
</html>
Step 1: Use a database :-)
No, but really, since you are storing the entire line as the value of the checkbox, you can compare that to the line in the file and update your visit field for matching lines ...
For example, in your processing file:
$filename = "properties.txt";
$data = file($filename, FILE_IGNORE_NEW_LINES);
$checked = $_POST['box'];
foreach($data as $id => $line){
if(in_array($line, $checked)){
//Explode the line into parts
$tmp = explode(',', $line);
//Increment the visit field
$tmp[3]++;
//Put the updated data back in the file data array
$data[$id] = implode(',', $tmp);
//Unset the tmp array
unset($tmp);
}
}
//implode the data back into a text block
$data = implode("\n",$data);
file_put_contents($filename, $data);
This is untested, but should yield what you are looking for ...
As a side note, you do not have to do the fopen call to use the file function. It will open and read the file.
EDIT: Since it appears that visit is the last column in each row and without any flags, the file function will keep the newlines at the end of each line, I added the appropriate flag to the file function.

Categories