How to show php string in html input - php

I have a flat file TestFile.txt that has about 40 lines of data, each item on a separate row, so 40 lines. I have a PHP code that finds the row containing a string I want to find using using $Search_String. Then displays only the row containing $Search_String. This works exactly as I want. However; it displays the result in text area. How do I display the result into a label box? The php reads the flat just as I would expect. I have 2 html input fields, but the string $line only contains data inside the if statement. Any help with this would be great!
Here is part of my flat file, filename is TestFile.txt:
RXFrequency=432675000
TXFrequency=432675000
RXOffset=260
TXOffset=120
Network=mnet.hopto.org
Password=8Yg81xrqK0313zt
Latitude=34.657783
Longitude=-3.784595
Port=62021
Here is my PHP:
<!DOCTYPE html>
<html>
<body>
<?php
$line = '';
?>
<input type="text" ID="message" value="<?php echo $line;?>"/>
<?php
// Place text to look for in string $Search_String.
// The $Search_String will remain hard coded in my production
// code. The users will not be able to select $Search_String.
$Search_String = "RXF";
// Identify Text File, open File and Read the File.
$MyFile = fopen("TestFile.txt", "r") or die("Unable to open file!");
$found= "False";
// Create the while loop. Test each line with the if statement,
// looking for $Search_String, and place the result into string $line.
// Next, echo string $line which containes the found line in the
// flat text file. It will return the entire line even from a
// partial $Search_String, which is what I want.
while ( $line = fgets( $MyFile ) )
{
if ( str_contains( $line, $Search_String ) )
{
echo $line;
echo $Search_String;
}
}
// Properly close the text file.
fclose($MyFile);
?>
<input type="text" id="message" value="<?php echo $line;?>"/>
</body>
</html>
This code does properly open the flat text file, it does the search and finds
the line containing the data I am trying to retrieve. I see the correct gata using echo in the if statement. Now I need to place the found data into the html input text box. The string $line seems to contain no data outside the if block of code. Can I make the variable $line static or global so the data is available throughout the code? Or am I using the html input text improperly? I think I do need to use input text, because I want to be able to modify the data and then write the line back to the flat file.
Thanks for any suggestions,
Mitch

This is a small grasp of your code including the proposed solution to loop through and show all the lines matching the criteria from your file:
<?php
/*...*/
$lines = [];
while ( $line = fgets( $MyFile ) ) {
if ( str_contains( $line, $Search_String ) ) {
//here you are keeping track of each line matching criteria
$lines[] = $line;
//echo $line;
//echo $Search_String;
}
}
?>
<?php foreach($lines as $line): ?>
<input type="text" value="<?= $line; ?>"/>
<?php endforeach; ?>

Related

PHP write to flat text file. New to PHP, learning. I have the read working. Need to write back updates

I have a flat file, TestFile.txt, that contains about 200 lines. Each item is a separate row. I show a partial of the contents of the TestFile.txt file below. I have PHP code working that reads TestFile.txt exactly as I need. The PHP read code searches the TestFile.txt, locates the line I wish to read, and places the result into an html input box. It parses the text after the = in the line, and only displays the data found after the =. Just as I need. Now I need to change the data in the html input box, and write the change back to TestFile.txt, and only update the text after the =. I show the PHP read code below. I have not a clue how to do what I need. I am a little over a week studying PHP. Any help with writing is much appreciated.
Thanks,
Mitch
Partial TestFile.txt:
RXFrequency=432675000
TXFrequency=432675000
RXOffset=260
TXOffset=120
Network=mnet.hopto.org
Password=9Yg81prqL0363zt
Latitude=34.657783
Longitude=-3.784595
Port=62021
Part of the PHP:
<!DOCTYPE html>
<html>
<body>
<?php
// Place text to look for in string $Search_String.
// The $Search_String will remain hard coded in my production
// code. The users will not be able to select $Search_String.
$Search_String_1 = "RXOff";
// Identify Text File, open File and Read the File.
$MyFile = fopen("TestFile.txt", "r") or die("Unable to open file!");
$found= "False";
// Create the while loop. Test each line with the if statement,
// looking for $Search_String, and place the result into string $line.
// Next, echo string $line which containes the found line in the
// flat text file. It will return the entire line even from a
// partial $Search_String, which is what I want.
/*...*/
// Next, let us build the array.
$lines = [];
while ( $line = fgets( $MyFile ) ) {
if ( str_contains( $line, $Search_String_1 ) ) {
//here you are keeping track of each line matching the criteria.
$lines[] = $line;
// This explode function will split the string contained
// in the $line variable at the =. Text left of the = is
// placed into the $key variable. Text right of the = is
// placed into the $value variable.
[$key, $value] = explode("=", "$line");
// echo $key; // RXOffset;
// echo $value; // 260;
//echo $line;
//echo $Search_String_1;
}
}
?>
<?php foreach($lines as $line): ?>
<?php endforeach;
// Properly close the text file.
fclose($MyFile);
// Get string $value from the explode code above.
?>
<label>RXOffset: <input type="text" id="message" value="<?php echo $value;?>"/></label>
<?php
</body>
<html>
Hope this gives enough information. Feel free to comment questions.
Thanks,
Mitch
This is what appears on the browser when I execute this PHP:
RXOffset: 269
Label Data

How to write response into label box

I have a flat file TestFile.txt that has about 40 lines of data, each item on a separate row, so 40 lines. I have a PHP code that finds the row containing a string I want to find using using $Search_String. Then displays only the row containing $Search_String. This works exactly as I want. However; it displays the result in text area. How do I display the result into a label box?
Here is part of my flat file, filename is TestFile.txt:
RXFrequency=432675000
TXFrequency=432675000
RXOffset=260
TXOffset=120
Network=mnet.hopto.org
Password=8Yg81xrqK0313zt
Latitude=34.657783
Longitude=-3.784595
Port=62021
Here is my PHP:
<?php
// Place text to look for in string $Search_String.
// The $Search_String will remain hard coded in my production
// code. The users will not be able to select $Search_String.
$Search_String = "Lon";
// Identify Text File, open File and Read the File.
$MyFile = fopen("TestFile.txt", "r") or die("Unable to open file!");
$found= "False";
// Create the while loop. Test each line with the if statement,
// looking for $Search_String, and place the result into string $line.
// Next, echo string $line which containes the found line in the
// flat text file. It will return the entire line even from a
// partial $Search_String, which is what I want.
while ( $line = fgets( $MyFile ) )
{
if ( str_contains( $line, $Search_String ) )
{
echo $line;
break;
}
}
// If the string $Search_String was not found, show a message
if(!$found)
{
echo 'No match found';
}
// Properly close the text file.
fclose($MyFile);
?>
The PHP code above returns:
Longitude=-3.784595
Just what I want, but I need it displayed in text box, or label box.
You need to print the answer as html
<?php
// Place text to look for in string $Search_String.
// The $Search_String will remain hard coded in my production
// code. The users will not be able to select $Search_String.
$Search_String = "Lon";
// Identify Text File, open File and Read the File.
$MyFile = fopen("TestFile.txt", "r") or die("Unable to open file!");
$found= "False";
// Create the while loop. Test each line with the if statement,
// looking for $Search_String, and place the result into string $line.
// Next, echo string $line which containes the found line in the
// flat text file. It will return the entire line even from a
// partial $Search_String, which is what I want.
while ( $line = fgets( $MyFile ) )
{
if ( str_contains( $line, $Search_String ) )
{
echo "<div style="
border: double;
">".$line."</div>";
break;
}
}
// If the string $Search_String was not found, show a message
if(!$found)
{
echo 'No match found';
}
// Properly close the text file.
fclose($MyFile);
?>

PHP Read Line From Text File, Only Selected Line

I am trying to search a text file for a string, and then display only the one line that was found. Would like to display the found line in a label box. My PHP is really weak. I got the following code working which will display the first line in the text area. Below is the contents of the text file: test.txt
First line
Second Line
Third Line
Fourth Line
My code is as follows:
<!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
</body>
</html>
This code returns First Line into the text area, so how can I return First Line to
text box, label?
Any pointer toward the right direction?
Thanks
Mitch
You'd want to continue fgets($file) in a loop, and checking if the search string is in the result, then when the search string is found, echo the line. Something like this maybe...
while ( $line = fgets( $myfile ) ) {
if ( str_contains( $line, $search_string ) ) {
echo $line;
break;
}
}
Note that str_contains is php 8 and up only. There are other methods for lower versions.
Also consider that perhaps a database would be better for this type of operation rather than using a flat file...

I need to do some modifications in a part of a sentence in a txt file with forms with PHP

I really need your help!
In advance sorry for my english...
I need to edit a .txt file with a PHP file, the modification in the txt file need to come from a form with the method "post"so,
my txt file look like this :
tour.name = something
image_foo = name of the image
I need to read the txt file line by line, split every line as an array; and split every line in an other array like
tour.name <= array key one / " = " <= explode the sentence with " = " / something <= array key two, My code need to check if array key one == "tour.name" and if it's "tour.name" change the "something" with the $_POST['tourname'].
In my PHP file i've wrote that :
<form action="" method="post">
<label for="tourname">Titre:</label>
<input type="text" id="tourname" name="tourname"><br><br>
<input type="submit" value="Submit">
</form>
<?php
$myArray = array();
$file = fopen("file.txt", "r+");
while (!feof($file)) {
$line = fgets($file);
$myArray[] = explode(' = ', $line);
}
$arr_length = count($myArray);
$actualTitle = $myArray[0][1];
$modifiedTitle = $_POST['tourname'];
$modifiedTitle .= PHP_EOL;
for ($i=0; $i<$arr_length; $i++){
switch($myArray[0][0]){
case "tour.name":
$myArray[0][1] = str_replace($actualTitle, $modifiedTitle, $myArray[0][1]);
fseek($file, 12);
fwrite($file, $modifiedTitle);
break;
}
}
fclose($file);
?>
PS: My code need to be not precise like mine in : $myArray[0][0] because the code need to be modulable, the txt file can be changed and not have the same number of lines, and not in the same order.... The code need to check if the first part of the sentence = "tour.name" but the tour.name in a future can be on the line 30 for example.
If someone can help me please!
Thank you
If I understood correctly that you simply wish to replace an existing value from a key=value pair where key==tour.name then you can simplify your code quite drastically. I notice that you use a switch expression which suggests that your end goal is beyond what you describe in the question but the following can easily be modified to accomodate...
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['tourname'] ) ){
# assign POSTed value as variable for convenience
$tourname=$_POST['tourname'];
# always easier to use the full path
$file=__DIR__ .'/file.txt';
# read the file into an array - makes it easier to read, line by line
$lines=file( $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
#iterate through all lines
foreach( $lines as $i=> $line ){
# split the line by the delimiter `=`
list( $param, $value )=explode( '=', $line );
# basic comparison test
if( trim( $param ) == 'tour.name' ){
# find the position in the array where this current line occurs
$pos=array_search($line,$lines);
#generate new content using POSTed value
$line=sprintf('%s=%s',trim($param),trim($tourname));
#splice the new value into the original position
array_splice($lines,$pos,1,$line);
}
}
# save the text file
file_put_contents($file,implode(PHP_EOL,$lines));
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>edit textfile</title>
</head>
<body>
<form method='post'>
<input type='text' name='tourname' />
<input type='submit' />
</form>
</body>
</html>

PHP Loop - Extract Data from CSV and array with echo'd HTML

This is a totally experimental question, but if answered it will save me hours of manual HTML mark up.
In theory it should work, but can appreciate advice if I'm talking rubbish.
I need a loop to pull column data from columns in a CSV spreadsheet, and echo them in HTML mark up.
I can't write PHP but this is how I envisage the loop work...
<?php
// here it needs to load the CSV file and get the column data and output them as variables (I guess)
echo <div id="interactive-map">
// here a loop needs to begin to output this line off HTML...
// with the arrayed variables...
<div id="[varible-1]" class="[varible-2]" title="[varible-3]"><span>[varible-3]</span></div>
// loop finished once no more rows left in CSV
echo </div>
?>
So the result should look like this...
<div id="interactive-map">
<div id="1" class="free" title="Uber"><span>Uber</span></div>
<div id="2" class="free" title="Howdy"><span>Howdy</span></div>
<div id="3" class="free" title="Love"><span>Love</span></div>
<div id="4" class="free" title="Gimme"><span>Gimme</span></div>
<div id="5" class="free" title="Totally"><span>Totally</span></div>
<div id="6" class="free" title="Spank"><span>Spank</span></div>
</div>
The CSV files looks like this...
(source: motocom.co.uk)
Any help or advice would be TRULY amazing! Thanks
// UPDATE BELOW FOLLOWING FIRST ANSWER
My CSV below viewed as text...
id,class,name
1,free,Uber
2,free,Howdy
3,free,Love
4,free,Gimme
5,free,Totally
6,free,Spank
The PHP below...
<?php
$file = fopen('file.csv', 'r');
$fields = array();
if ($file) {
while (($data = fgetcsv($file)) !== false) {
if(empty($fields)) {
$fields = $data;
continue;
}
$row = array_combine($fields, $data);
$output = sprintf("% is ID, % is CLASS, % is NAME",
$row['id'],
$row['class'],
$row['name']);
echo $output;
}
fclose($file);
}
?>
It's not quite working properly, what am I doing wrong?
With regards to adding the HTML, I put the mark up inside where the echoed text is and it gets confused :-/
It is echoing stuff but not the desired info from the csv.
To read the file, the easiest is to use the built-in fgetcsv in a loop. You can cook up your own parsing code, but it's really thankless work to make it behave correctly in the presence of field delimiters and escaped characters.
After reading the names of the CSV fields (first iteration) and their values for each row (subsequent iterations), you can use sprintf or vsprintf to easily construct an HTML string to output.
For example:
$file = fopen('php://stdin', 'r'); // or open any other file you want
$fields = array(); // this holds the name of the fields, read from the 1st row
if ($file) {
while (($data = fgetcsv($file)) !== false) {
// If this is the first row, we assume it holds field names.
// So just remember what they are and loop to the next.
if(empty($fields)) {
$fields = $data;
continue;
}
// Subsequent rows are assumed to contain data.
// array_combine associates the data in the current row with the field
// names from the first row, allowing us to refer to them using those
// names and be independent of the order the fields appear in the input.
$row = array_combine($fields, $data);
// Format output conveniently with sprintf
$output = sprintf("%s is %d years old.\n",
$row['name'],
$row['age']);
echo $output;
}
fclose($file);
}
See it in action.

Categories