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

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.

Related

How to show php string in html input

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; ?>

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 split csv data in two parts.?

Is it possible to export csv data in to two parts:
From the below image i have two things to be considered
1. summery
2. Detail information
I worked with only 2nd type is it possible to do like 2 batches(like shown in image)..?
please suggest any alternate idea if you got.
Example:
summary header
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
/*summery data */
Details header
$titleDetail = array('student','passout','branch','percentage watched','student email');
/*Details data */
In this case how can i export the data..?
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach($data as $k=>$res){
fputcsv($output,$res);
}
You need to prepare array for each line. see my inline comments.
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
$titleSummeryData = array('Number System','50%','40%',....); // fill remaining data.
$output = fopen('php://output', 'w');
// put first table
foreach($titleSummery as $key=>$val){
fputcsv($output,array($val,$titleSummeryData[$key]));
}
// begin second table
// put all title/header
fputcsv($output,$titleDetail);
// For second table i assume that you have data in 2D array
foreach($titleDetailsData as $row){
fputcsv($output);
}
fclose($output);
You direction is good, you just need to understand that each call to fputcsv prints a line, so you'll need to call it for each row in the first batch of data also, for example:
fputcsv($output,"course name","php for dummies");

How to filter on a word in a specific column of a csv file with PHP

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.

PHP to remove last line of CSV file

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.

Categories