PHP thousand separator formatting for generated page from xlsx - php

Ty mail2bapi, :)
Im using SimpleXLSX and example script below in code i added this $x = number_format($r);
Just need the numbers to have thousand separator
252252732
to
252,252,732
IM not good with PHP, really appreciate any help
Plus some columns are empty and dates like so 23.01.2020, I think this is what is causing the issue
XMLS File
simplexlsx
Error: number_format() expects parameter 1 to be double, array given in
Error: implode(): Invalid arguments passed
<?php
require_once 'SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
foreach( $xlsx->rows() as $r ) {
$x = number_format($r);
echo '<tr><td>'.implode('</td><td>', $x ).'</td></tr>';
}
echo '</table>';
// or $xlsx->toHTML();
} else {
echo SimpleXLSX::parseError();
}
?>

You are not using number_format() function correctly. Change following code from -
$x = number_format($r);
to
$x = number_format($r, 0, ".", ",");
for more information visit PHP number_format
EDIT
As you mentioned your row could have a different type of values, it is better to check the value for numeric.
Try this code
<?php
require_once 'SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
foreach( $xlsx->rows() as $rowValue ) {
echo "<tr>";
// As $rowValue is an array
foreach($rowValue as $value){
// Check for number_format
if(is_numeric($value)){
$x = number_format($value, 0, ".", ",");
echo "<td>".$x."</td>";
}else{
echo "<td>".$value."</td>";
}
}
echo "</tr>";
}
echo "</table>";
// or $xlsx->toHTML();
} else {
echo SimpleXLSX::parseError();
}
Hope these resolve your issue.

Related

Displaying data from arrays in a dynamic table PHP

I have a file with 20 pictures of country artists, and a text file with their websites. I'm trying to display this data in a 4 row 5 column table using PHP.
I try to use a foreach loop that iterates for every 5 elements in the array
(to load each row one by one)
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
<table>
<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td></tr>
</table>
Ive been trying to figure out how to load the images into the array, but having no luck. Im starting to think i must put the reference to the file location in the array,but i am not sure.
$colsToDisplay = 5;
$CountryArtists = array("C:\Users\THEFOLDER\images");
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", RTravis", "STwain", TKeith", TMcgraw");
$filename = "C:\Users\THEFOLDER\images";
I'm relatively new to PHP and really just need to know how to load my images and how to make this table show up correctly.
EDIT:
I added echo to the table lines but it just shows echo in the browser output:
" echo " $CountryArtists[$Value] $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo "" } ?>
My code now looks like this:
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
echo "<table>"
echo "<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td></tr>"
echo "</table>"
}
I feel like I'm doing strong wrong, would be so grateful to have it pointed out to me.
FULL FILE
<!DOCTYPE HTML>
<html>
<body>
<?php
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
$count = count($ArtistImages);
$cols = 6;
$div = (int) $count / (int)$cols;
$diff = ceil($div);
echo
$fin = $cols * $diff;
$a = 1;
echo '<table>';
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
?>
</body>
</html>
I think you may be looking for something similar to this algorithm. It adds a row every 5 values. You will want to do a divisor make it ceil() to make it add any required empty cells. You can do this foreach if you do <ul> and <li> and use CSS to make them display like a table. Then you don't need to calculate extra cells.
$i = 1;
echo '<table>';
foreach($array as $value) {
if($i == 1)
echo "<tr>";
echo '<td>'.$value.'</td>';
if($i == 5) {
echo "</tr>";
$i=0;
}
$i++;
}
echo '</table>';
EDIT:
Here is a more practical version based on yours:
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
// Count total artists in array
$count = count($ArtistImages);
// Choose how many to display per row
$cols = 6;
// Divide the total by the columns
$div = (int) $count / (int)$cols;
// Round up (incase the number will produce empty cells
$diff = ceil($div);
// Mulitply the final numbers
$fin = $cols * $diff;
// Create an autoincrementer to keep track of next rows
$a = 1;
echo '<table>'.PHP_EOL;
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
// You need to see if this artist is populated. If not, make empty
// If left without this it will have a warning saying not exists
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
In the php file you need to echo the data you want.
However if you in the php file you can close php like this.
? >
And write html code.
When you want to display php attributes you again need to open a php like this:
and continue like this...
Php fcan only return string or json data
Let me know if it work for you....

While loop inside for loop not working while fetching mysql rows

<?php
echo '<table>';
for($i=1;$i<=12;$i++)
{
echo '<tr>';
while($row5=mysql_fetch_array($result5))
{
if($row5[3]=='monthly')
echo '<td>'.$row5[3].'</td>';
else if($row5[3]=='quarterly')
echo '<td rowspan="3">'.$row5[3].'</td>';
else if($row5[3]=='halfyearly')
echo '<td rowspan=""="6">'.$row5[3].'</td>';
else
echo '<td rowspan="12">'.$row5[3].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
This code is printing only one row instead of 12 rows. Please help me. I am doing this for managing student fees. I am stuck at the logic.
Create an array with sql result before :
$data = array();
while( $row5 = mysql_fetch_array($result5) )
$data[] = $row5;
Then replace this : while($row5=mysql_fetch_array($result5))
foreach ( $data as $row5 ) {
if($row5[3]=='monthly')
echo '<td>'.$row5[3].'</td>';
// ...
}
PS : Use mysqli_* instead of mysql_* which is deprecated

PHP explode multidimensional array

I am using file_get_contents() to import a text file.
In the text file, the format goes as below (example):
3434,83,8732722
834,93,4983293
9438,43933,34983
and so forth... basically it follows the pattern: integer, comma to split it, second integer, another comma to split it, third integer, then a new line begins. I need to get this into a table with the format following accordingly. So in other words, I would have a 3 column table and each new line in the text file would be a new row in the table.
This must be transcoded into a simple html table with <table> <tr> and <td>
I have never worked with multidimensional arrays and splitting text with that. This is why I'm seeking assistance. I really appreciate it! :)
You can do following :
$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
$explodedByComma = explode(',', $brExplode);
$table .= "<tr>";
foreach ($explodedByComma as $commaExploded) {
$table .= "<td>" .$commaExploded. "</td>";
}
$table .= "<tr/>";
}
$table .= "</table>";
echo $table;
abc.txt has data in following format :
3434,83,8732722
834,93,4983293
9438,43933,34983
<?php
$file = 'path/to/file.txt';
echo '<table>';
while(!feof($file)) {
$line = fgets($file);
echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
}
echo '</table>';
?>
Try this:
Read the file into an array and then column'ize it by processing each line of the array by passing it through array_walk.
<?php
function addElements( &$v, $k ) {
$v1 = explode( ',', $v ); // break it into array
$v2 = '';
foreach( $v1 as $element ) {
$v2 .= '<td>'.$element.'</td>';
// convert each comma separated value into a column
}
$v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}
// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements,
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
<head></head>
<body>
<table border="0">
<?php echo implode('',$file);?>
</table>
</body>
</html>
Hope it helps. See the php doc for file and array_walk. These are simple and convenient functions.

How to collect functions results into one array and return this array?

My php function looks like that
function generateTour ($lang, $db)
{
echo '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0) echo '<tr>';
echo '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">';
echo '</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1) echo '</td></tr>';
else if($i%3==0) echo '</td></tr><tr>';
$i++;
}
echo '</table>';
}
As you see it echoes result line by line. Not all at once. I want to collect all variables to one array and return this array. Is it possible? how to do it?
Please don't post your ideas about security holes .. etc. I'm filtering $title, $txt varibales against sql injections. (i have array for of possible field names. My filter function checks theese variables' values every time. )
$data = array();
while ($row = $result->fetchObject()) {
$data[] = $row;
}
Is the absolutely most basic method of cacheing a result set in an array. You'd just modify this to store your generated html instead.
Try this:
function generateTour ($lang, $db)
{
$output = '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0)
{
$output .= '<tr>';
}
$output .= '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">
</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1)
{
$output .= '</td></tr>';
}
else if($i%3==0)
{
$output .= '</td></tr><tr>';
}
$i++;
}
$output .= '</table>';
return $output;
}
Edit:
Now it's easier to read the code. This solution put all content in one variable. You don't need a array.
You can use ob_start() and ob_get_clean() to buffer all output into a variable, then output that variable, like this:
ob_start();
print "Hello"; // Prints to buffer instead of screen
$out = ob_get_clean(); // Contains: Hello
echo $out; // Prints: Hello

Loop separated text into variables

Im using this PHP to display the contents or text files held in a directory, the text files all follow the same format.
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
There are 7 $items in each text file:
tag,name,description,text1,text2,text3,date
So instead of outputting $item, can i give each its own variable?
Thanks.
Try this:
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
Try:
while(list($tag,$name,$desc,$text1,$text2,$text3,$date) = each($items){
// do something
}
Treat the text file as a csv file seperated by the ¬ char.
http://www.php.net/manual/en/function.fgetcsv.php
Then you can either rely upon a header file to describe the fields ( columns ) or access them numerically.

Categories