I am trying to display a CSV file in a paginated format using PHP. I am using HTML to display the header information from CSV. I am using HTML because if I go to the remaining pages, the header remains in the table. However, in the first page alone I get the header information twice. I tried to remove it using str_replace and preg_replace but to no luck. This is the code I have so far.
<?php
$names = file('demo.csv');
$page = $_GET['page'];
//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default is 1)
$pagedResults = new Paginated($names, 50, $page);
$handle = fopen('demo.csv', 'r');
if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
}
echo "<table id='kwTable' border='4' bgcolor='#adb214' style='float:center; margin:100'>";
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
?>
<tbody id="kwBody">
<?php
//when $row is false loop terminates
while ( $row = $pagedResults->fetchPagedRow())
{
echo "<tr><td>";
//echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
//Here I am getting the header information from the CSV file twice.
$row1 = str_replace( ',', "</td><td>", $row );
echo $row1;
echo "</td></tr>";
}
fclose($handle);
echo "</table>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
If you have just one header row at the top of the CSV then you just need to skip the row on first pass:
$header = true;
if (!$page) $page = 1;
while ( $row = $pagedResults->fetchPagedRow())
{
if ($page == 1 && $header) {
$header = false;
continue; // Skip this header row
}
echo "<tr><td>";
//echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
//Here I am getting the header information from the CSV file twice.
$row1 = str_replace( ',', "</td><td>", $row );
echo $row1;
echo "</td></tr>";
}
Related
I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17
?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.
What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.
here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.
<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';
function get_row($csv, $row) {
$handle = fopen("$csv", 'r');
$counter = 0;
$result = '';
while ( ($data = fgetcsv($handle)) !== FALSE ) {
$counter++;
if ( $row == $counter ) {
$vin_num="$data[12]";
$model="$data[10]";
$make="$data[9]";
$year="$data[8]";
ob_start();
?>
<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>
<?php
$output = ob_get_clean();
ob_flush();
return $output;
}
}
}
?>
<?php
function extract_data($file)
{
$raw = file($file); // file() puts each line of file as string in array
$keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
// Look through the rest of the lines and combine them with the header
$data = [];
foreach ($raw as $line) {
$row = str_getcsv($line);
$data[] = array_combine($keys, $row);
}
return $data;
}
function get_record($data, $vin)
{
foreach ($data as $record) {
if ($record['VIN'] === $vin)
return $record;
}
return null;
}
$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
echo '<h1>No VIN provided</h1>';
exit;
}
$record = get_record($data, $vin);
if ($record === null) {
echo '<h1>No record found</h1>';
exit;
}
echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';
echo '<pre>' . print_r($record, true) . '</pre>';
If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?
Hopefully someone can assist, I currently coding pages for a game manual and i'm using two functions I found here, one to pull text/formatting from a html file and the other to pull data from a CSV file and insert it into a table. If I have more than one section to include in the page I have been duplicating the code. An example of the result can be found here
As you can see the page shows three sections and this is the result I want. What i'm wondering is if there is a more efficient way than how I am currently doing it which is by copying the code and just altering the variables for every file I want to import? As you can see the variable name is set by the page name. Below is the code I am using.
//function to display csv as table
function csvimport($filename, $header = false)
{
$handle = fopen($filename, "r");
echo '<table id="subman">';
//display header row if true
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
I then use the following to select the CSV file to use and display as a table.
csvimport("$data", "true");
defined by the variable $data
//get page name from link or use manual as default
$page = $_GET['page'] ?? 'manual';
//combine page name with suffix and set page variables
$data = "{$page}.csv";
I use similar for the html as shown below.
$myfile = fopen("$text", "r") or die("Unable to open file!");
echo fread($myfile, filesize("$text"));
fclose($myfile);
So I can get multiple files to display in order I copy the code and add these variables.
$data = "{$page}.csv";
$data2 = "{$page}2.csv";
$data3 = "{$page}3.csv";
Hopefully I have explained myself and what I am trying to ask.
Thank you all in advance for reading :)
You should learn how modern web frameworks work. They separate the view, the model and the controller. The model is the logical architecture of your application, the controller is the code to route and render each page, and the view is all the html output and the styling.
Viewing your code I would separate first the view. Here I have done a first step of what I'm saying. It is only a first step, I recommend you to learn a few (a lot of) programming concepts, to use composer components, to look deeply at one of the million php (micro)frameworks or to roll your own. There is a lot of oportunities nowadays to do php the right way.
Separation of the controller and the templates
index.php
function csvimport($filename, $delimiter = ',') {
$handle = fopen($filename, "r");
$output = [];
while ($csvcontents = fgetcsv($handle, 1024, $delimiter)) {
$output[] = $csvcontents;
}
fclose($handle);
return $output;
}
function tpl($fileName, $data = false) {
$rendered = "";
if (file_exists($fileName)) {
ob_start();
extract($data);
require($fileName);
$rendered = ob_get_contents();
ob_end_clean();
}
return $rendered;
}
$data['header'] = true;
$data['csvcontents'] = csvimport(CSV_FILE, ';');
echo tpl('table.tpl.php', $data);
table.tpl.php
<table id="subman">
<?php
$first = true;
foreach ($csvcontents as $row) :
if ($first) :
$first = false;
if ($header) :
$tag = 'th';
else:
continue;
endif;
else:
$tag = 'td';
endif;
?>
<tr>
<?php foreach ($row as $column) : ?>
<<?= $tag ?>><?= $column ?></<?= $tag ?>>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
The index has a few functions to read csv and render any template and the template holds all the html output. This is only a first approach, far for being a production ready code, use at your own risk and never trust user input
I am new to PHP and I am trying to display the CSV data in my web page with pagination option.This is the code I have so far.
<?php
$names = file('demo.csv');
$page = $_GET['page'];
//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default is 1)
$pagedResults = new Paginated($names, 20, $page);
echo "<ul>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
$row1 = str_replace( ',', "\t", $row );
echo "<li>{$row1}</li>";
}
echo "</ul>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>
I was having issues with commas getting displayed in my output. However, I have resolved using the str_replace function. Now, I wish to show the data elegantly in a tabular format. I tried the below code that I saw in another link.
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
<table>
<tr>
$row1 = str_replace( ',', "\t", $row );
<td><?php echo "<li>{$row1}</li>";?></td>
</tr>
</table>
}
echo "</ul>";
However, I am not getting output in my screen. Can someone please guide me in the right direction?
<?php
$names = file('demo.csv');
$page = $_GET['page'];
//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default is 1)
$pagedResults = new Paginated($names, 20, $page);
echo "<table border=\"1\">";
//use the following line to manually display column names,
//if they're not in the 1st row of the CSV file
echo "<tr><td>Column 1 name</td><td>Column 2 name</td><td>Column 3 name</td></tr>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
echo "<tr><td>";
$row1 = str_replace( ',', "</td><td>", $row );
echo $row1;
echo "</td></tr>";
}
echo "</table>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>
You are mixing HTML and PHP a little to loosely. Fix like this:
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
echo "<table>";
echo "<tr>";
$row1 = str_replace( ',', "\t", $row );
echo "<td>";
echo "<li>{$row1}</li>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
echo "</ul>";
or like this:
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
?>
<table>
<tr>
<?php $row1 = str_replace( ',', "\t", $row ); ?>
<td><?php echo "<li>{$row1}</li>";?></td>
</tr>
</table><?php
}
echo "</ul>";
The first one obviously having the preference, as it as much more readable.
Your tables are not placed correctly in the loop.
Please refer the following code:
<table><?php
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
?>
<tr>
<?php
$row1 = str_replace( ',', "\t", $row );
?>
<td><?php echo $row1;?></td>
</tr>
<?php
}
?></table>
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);
I am trying to use data from an excel spreasheet to populate an html table using php. I am a beginner at PHP. I have tried to use code from other questions, and they were close but not quite what I needed. The excel document will be periodically updated by another person.
Here's an example of code I've used:
$file = file("/calendar.txt");
print "<table>
<tr><td>Date</td><td>Start Time</td><td>Venue</td><td>Description</td></tr>";
foreach($file as $line){
$line = trim($line);
$split = mb_split("\t",$line);
print "<tr><td>$split[3]</td><td>$split[4]</td><td>$split[5]</td><td>$split[6]</td></tr>";
}
print "</table>";
?>
But the above example does not allow for auto-population. So I tried this:
<table>
<?php
if (($handle = fopen("/calendar.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
print "<tr><td> $data[$c] </td></tr>";
}
}
fclose($handle);
}
?>
</table>
But I couldn't get the columns I wanted. Plus both examples did not allow for a new row/column created at the end of the last column from the source file (i.e. the data from the last column in the first row is combined with the first column of the second row).
I would also like to echo the line, "There are no upcoming dates currently. Please check back soon!" if there is no information to display. And is there a way to do a colspan in php? Here are my failed attempts: http://www.tonejones.com/calendar3.php
I want the table to look like this: http://www.tonejones.com/calendar.php
To populate Data from Excel to Table. First We need to retrieve all data into Array then we will render all Array values into table.Get reference to retrieve data into array. https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php. IF you get array then use below code
<table>
<?php foreach($rows as $value){ ?>
<tr>
<td><?php echo $value; ?></td>
</tr>
<?php } ?>
</table>
Your block should go around the collection of cells, not each individual cell:
print "<table>
<tr><td>Date</td><td>Start Time</td><td>Venue</td><td>Description</td></tr>";
<?php
if (($handle = fopen("/calendar.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
$num = count($data);
print "<tr>";
for ($c=3; $c < $num; $c++) {
print "<td> $data[$c] </td>";
}
print "<tr>";
}
fclose($handle);
} else {
print "<tr><tdcolspan="4">
There are no upcoming dates currently. Please check back soon!
</td></tr>";
}
?>
</table>