Populate table from excel file using php - php

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>

Related

Sort a csv file on a column and display in php

I have a csv file (test.csv) like this (no header)
name2,age23,city5
name5,age55,city3
name3,age36,city4
name1,age18,city2
name4,age44,city1
I want to sort on name column like this ascending or descending order
name1,age18,city2
name2,age23,city5
name3,age36,city4
name4,age44,city1
name5,age55,city3
<?php
if (($handle = fopen("test.csv", "r")) !== FALSE) {
$i=1;
$row=0;
$csv_row = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$csv_row = $data;
?>
<tr>
<td><?php echo $i;?> </td>
<td><?php echo $csv_row[1];?></td>
<td><?php echo $csv_row[2];?></td>
<td><?php echo $csv_row[3];?></td>
</tr>
<?php $i++;
}
fclose($handle);
}
?>
How to sort data ($csv_row) on a column (Name) before print? Suggested answer is not working for me.
I am new in php. Many suggestion available but they are not working properly . Please give a simple solution.
Thanks in advance.

Create/fill form with values from uploaded CSV

I've decided that to accomplish my task, I need to take the CSV file that is uploaded on my first page, and build a form from it filling the inputs with the CSV values.
I have a functioning CSV upload, but this is to view the CSV and make edits to the fields before saving. I have a while loop that I think I should build the form inside. The only trick is that I've built a CSV data array that handles it upon upload and it's 229 elements long. I need to build the form names to mirror it, so I"ll essentilally be naming 229 form fields, which is fine. Here is the current code that successfully loads the CSV into a table when the button is clicked:
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
echo '<tr>';
foreach($row as $value) {
echo "<td>$value</td>";
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
}
So, that successfully shows the entire CSV (6 rows, 229 columns per row) for a preview. Now I just need to make each field editable and then insert the entire form upon submit. I know how to insert a form to a database, so now I just need an idea of how to build the form within the while loop and create the names for each input, as well as how to fill the inputs with the actual CSV data.
This is how you can create a form. Each form element is named like row1col1, row1col2, ro1col3 etc...
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo '<form>\n';
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
$colCount = 0;
echo '<tr>';
foreach($row as $value) {
echo "<td><input name='row".$rowCount."col".$colCount."' type='text' value='$value' /></td>";
$colCount++;
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
echo '<input type=\'submit\' value=\'Submit\' >';
echo '</form>';

find character in string from csv file using php?

I am really a newbie in php. I have a problem in doing this..
I have sample.csv file contains 3 rows: inbound(1st row), outbound(2nd row), and date(3rd row).
sample.csv
**inbound** **outbound** **date**
IN/15#001234 OUT/000000163-000000as 1/12/2014
IN/15#004323 NOT/000000141-00000043 1/14/2014
IN/15#005555 OUT/000000164-000000jk 1/15/2014
is it possible to display the all columns where 2ndrow is start with "NOT" and a number before char "-" is 141???
output:
IN/15#004323 NOT/000000141-00000043 1/14/2014
i dont know if it is possible... please help me..
I have a code below. But it only open the csv file...
$file = fopen('Master.csv', 'r');
echo "<table style='border: 2px solid black; text-align:left'>";
while (($line = fgetcsv($file)) !== FALSE) {
list($inbound, $outbound, $date) = $line;
echo "<tr>";
echo "<td>$inbound</td>";
echo"<td>$outbound</td>";
echo "<td>$date</td>";
echo "</tr>";
}
echo "</table>";
is it possible to display the all columns where 2ndrow is start with "NOT" and a number before char "-" is 141???
Inserting
if (preg_match('/^NOT/', $outbound)) continue;
after the list()... statement should be sufficient.
But your data does not look like being comma-seperated, rather than tab-seperated. And perhaps you mean columns when talking about rows at the beginning?
You can use strpos()
if ( strpos($outbound, 'NOT') !== false ) {
// "NOT" WORD FOUND IN STRING
}
Try this out. This will work with comma separated csv file.
echo "<table border = 1><tr><td>first</td><td>second</td><td>third</td></tr>"; //creating table
$handle = fopen('fe.csv', "r"); //open csv file
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) //read csv file row by row
{
//check both NOT and 141- in the string
if ( (strpos($data[1], 'NOT') !== false ) && (strpos($data[1], '141-') !== false )) {
//add required field data to table
echo "<tr>";
echo "<td>".$data[0]."</td>";
echo"<td>".$data[1]."</td>";
echo "<td>".$data[2]."</td>";
echo "</tr>";
}
}
echo "</table>"; //close table
?>

Remove the CSV header from display

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>";
}

php: using google csv, remove duplicate values populated in column

I am a newbie to php and have been searching tirelessly for a solution to this problem (i'll bet its a super simple solve too *sigh).
I am importing a .csv feed from a google doc. It is pulling in 2 columns, one for "name" and the other "location". I would like to remove duplicate "locations". since i am using fgetcsv, my understanding is that it is already sorting the data into an array. Ideally, it would omit the "location" duplicates so that the "names" look as though they are listed under the "location" they correspond to.
Here is what i have:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo $data[1];
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
ideally i would be able to use something like this:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo array_unique($data[1]);
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
Many thanks in advance for any help! :o)
This may work, assuming that the items in the array are grouped by location. It stores the last data item (location) and compares whether each item has that location. If it does, it prints it, otherwise it creates a new list item with the new location, and then prints the name underneath (I haven't tested it though):
$url = "the-url-to-my-csv-feed";
$handle = fopen($url, "r");
$lastdata = '';
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
if ($lastdata == '') {
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata = $data[1];
}
if ($lastdata != $data[1]) {
echo "</li>\n";
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata == $data[1];
}
echo $data[2] . "<br/>\n";
}
fclose($handle);
<? //PHP 5.4+
$url = 'url to your csv feed';
//Group people by same location first,
//not assuming csv is already sorted.
$namesByLocations = [];
//Because we're using \SplFileObject, when the reference goes out
//of scope at the end of the loop, the file pointer is never
//left open. This is true even if an exception is thrown
//in the middle of looping.
foreach(
\call_user_function(static function() use ($url){
$file = new \SplFileObject($url);
$file->setFlags(\SplFileObject::READ_CSV);
return $file;
})
as $array
){
//$array[1] is assumed to be location string
//$array[2] is assumed to be a name that is there.
$namesByLocations[$array[1]][] = $array[2];
}
foreach($namesByLocations as $location => $names){
//Protect against injection flaws,
//escape to destination's context. (html this time)
echo '<strong>' . \htmlspecialchars($location) . '</strong>';
echo '<ul>';
foreach($names as $name){
echo '<li>' . \htmlspecialchars($name) . '</li>';
}
echo '</ul>';
}
?>

Categories