I need to loop through some records within an excel file and output them as headings for an HTML table but I don't know what is the best approach as I am new to PHP.
Each the column headings begins as a Title followed by an index so you have:
Country1, Country2, Country3 ....through to Country50.
I would like to have a more automatic way to retrieve these values rather than stick to the
$result .= "$Country1";
each must also contain the id of the country which should also be converted into an array i.e. The other thing so they do not require to be printed if that's the case, so the results could be
<th id="Country1">Value of Country1</th>
<th id="Country2">Value of Country2</th>
<th id="Country3">Value of Country3</th>
<th id="Country8">Value of Country8</th>
<th id="Country24">Value of Country24</th>
<th id="Country30">Value of Country30</th>
What is the best "code light" approach to doing this?
Regards!
something like that should work:
<?php
$handle = #fopen("/tmp/myfile.csv", "r");
if ($handle) {
// first line should be the header, we make it an array of strings
if ( ($buffer = fgets($handle, 4096)) !== false )
$headers[] = explode(",", $buffer);
else
echo "Error: empty file...\n";
// second line should be the values, for each line we output the xml markups
while ( ($buffer = fgets($handle, 4096)) !== false )
{
$values[] = explode(",", $buffer);
if( count($headers) != count(values) )
echo "Error: the 2 lines do not have same number of columns...\n";
else
{
for( $i = 0 ; $i < count($headers) ; $i++ )
echo "<th id='".$headers[$i]."'>".$values[$i]."</th>\n";
}
}
else
echo "Error: second line empty...\n";
if ( !feof($handle) )
echo "Erreur: fgets() failed...\n";
fclose($handle);
}
?>
Related
I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}
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
?>
I'm creating a table using PHP from a CSV file.
I am trying to sort the output (DESCENDING) by one column from the CSV file which is: $line_of_text[13]
But I have no idea how to this as it is not as straight forward as sorting the output if I was using mysql.
This is my entire code:
<?php
$file_handle = fopen("MY-CSV-FILE.csv", "r");
print "<table style='width:100%; float:left;'>\n";
while (!feof($file_handle) ) {
//print '<tr>';
$line_of_text = fgetcsv($file_handle, 1024);
$line_of_text = str_replace('http', '<a href=""><img title="Click To Enlarge" class="fancybox" style="width:210px; height=210px; float:left;" src ="http', $line_of_text);
$line_of_text = str_replace('jpg', 'jpg"/></a>', $line_of_text);
$line_of_text = str_replace(',', '', $line_of_text);
$line_of_text = str_replace('PictureRefs', '', $line_of_text);
asort($line_of_text);
foreach($line_of_text as $key => $value)
print "<tr><td>".$line_of_text[9].'</td><td>'.$line_of_text[10].'</td><td>'.$line_of_text[2].'</td><td>'.$line_of_text[5].'</td><td>'.$line_of_text[6].'</td><td>'.$line_of_text[7].'</td><td>'.$line_of_text[8].'</td><td>'.$line_of_text[3].'</td><td>'.$line_of_text[4].'</td><td>'.$line_of_text[11].'</td><td>'.$line_of_text[12].'</td><td>'.$line_of_text[13].'</td><td>'.$line_of_text[14].'</td><td>'.$line_of_text[15]."</td></tr>\n<tr><td width='100%' colspan='100'><div style=' width:100%;'>".$line_of_text[16]."</div></td></tr>";
}
print '</table>';
fclose($file_handle);
?>
As you can see I have started doing this:
asort($line_of_text);
foreach($line_of_text as $key => $value)
but I don't think this is correct!
could someone please advise on this ?
any help would be appreciated.
You need to load all of your rows into an array, sort, and then echo the table. You need to split this into two loops.
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>";
}
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>