This question already has an answer here:
How to force PHP to read newlines and returns as <br>
(1 answer)
Closed 4 years ago.
I am having trouble creating a new line in a HTML table cell. The data is coming from a CSV file and each cell has multiple lines. I tried using '\n', '\r'but it's not working. I searched the forums but haven't found a solution. Any suggestions on how I can achieve this? Should I use a different function? Thanks..
The CSV Looks like this:
header,header,header,header,header
,,,,"title
aaaaaaa
bbbbbbb
ccccccc","title
ddddddd"
The code I am using outputs the file like this:
header header
title aaaaaaa bbbbbbb title ddddddd
ccccccc
I want it to output like this:
header header
title title
aaaaaaa ddddddd
bbbbbbb
ccccccc
The code I am using is from this thread: Dynamically display a CSV file as an HTML table on a web page
<?php
echo "<html><body><table>\n\n";
$f = fopen("my.csv", "r");
while (($line = fgetcsv($f, 0)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
I ended up using nl2br. Working code below.
<?php
echo "<html><body><table>\n\n";
$f = fopen("my.csv", "r");
while (($line = fgetcsv($f, 0)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo nl2br("<td>" . htmlspecialchars($cell) . "\n" . "</td>");
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
You can try the predefined constant PHP_EOL, which is «the correct 'End Of Line'» following the php docs.
In fact, "\n" is a typical unix end of line, and most windows don't well understand it. Php will take care of that with PHP_EOL.
echo "</tr>".PHP_EOL;
You can also try to use heredoc (EOF)
http://php.net/manual/en/reserved.constants.php
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Related
I have a csv file where fields are separated by semicolons. Inside each field we can have comma (decimal separator for numbers in italy is comma).
a sample data is:
15/01/2021;15/01/2021;ADDEBITO SDD;PAGAMENTO NEXI 8000640000030620818186 NEXI S.P.A. CORSO SEMP - ADDE BITO SPESE CARTA DI CREDITO ESTRATTO CONTO DEL : 31/ 12/2020 - UNCRITMMXXX IT500040000004107060966;1.501,2;;Uscita;
I explode this line by semicolon and then build a table row out of it:
while (($line = fgetcsv($f)) !== false) {
$row = $line[0];
$cells = explode(";",$row);
echo "<tr>";
foreach ($cells as $cell) {
echo "<td>";
echo htmlspecialchars($cell);
echo "</td>";
$cur_col_num+=1;
}
echo "</tr>\n";
The issue I have is that the string "1.501,2" is echoed as 1.501 loosing the decimals.
If the source is "1501.2" this is echoed correctly as "1501.2".
How do I keep the decimal if the separator is a comma? I have no control over the content of the csv that is coming from different sources and so I need to handle both situations.
EDIT: after some more tests I realized that actually for any line containg the comma it stops processing the line after the comma (ignoring the following fields). So in the example I never see "Uscita" in its table cell
EDIT 2: this is the output of my code on the browser for this specific line
CSV means "comma separated values", so fgetcsv() splits the line at , characters by default. Your file uses ; as the field separators, so you should tell fgetcsv() to use that instead.
Then you don't need to call explode() yourself.
while ($cells = fgetcsv($f, null, ';')) {
echo "<tr>";
foreach ($cells as $cell) {
echo "<td>";
echo htmlspecialchars($cell);
echo "</td>";
$cur_col_num+=1;
}
echo "</tr>\n";
}
I have found many threads to echo a CSV file as XML, but cannot work out how to filter rows and columns.
The code below does exactly what I want but the output is an HTML table.
I need help to create similar code for xml output.
Scenario
sitemap.csv
1,https://example.com/page1,monthly,1
7,https://example.com/page2,monthly,0.5
14,https://example.com/page3,monthly,0.5
21,https://example.com/page4,monthly,0.5
This is a static website where all pages are already created but should only appear in sitemap at rate of 1 per week ie 10 days after 09 Feb 2020 $launchdate only first two rows should be visible in sitemap.
1st column should not be echoed - it is used to determine if that row should be echoed at load time.
I have looked at many scripts to convert csv to XML but all of them display all columns. I have tried for hours to come up with a solution to create results in XML format.
I know final solution will need to include something like:
header("Content-Type: application/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' .PHP_EOL;
I know final solution will need to exclude the echo of date data at top - currently used for testing
I know final solution will need to replace the column descriptors
eg Loc will become <loc> URL </loc> then <lastmod> <changefreq> <priority>
======
Working code to echo HTML table
<?php
//Sources for this solution
// https://thisinterestsme.com/reading-csv-file-with-php/
// and & https://stackoverflow.com/questions/40285479/filtering-and-displaying-a-csv-file-with-php
// Final solution should be xml not HTML table
$date = date("Y-m-d"); // Todays Date
$date_number = strtotime($date); // Todays date as Integer
$launchdate_number = strtotime('2020-02-09'); //Launch Date as Integer 1581206400
$days_since_launch = ($date_number - $launchdate_number) / 86400; // Days since Launch date
// Echo data for testing, will not be in the final XML file
echo "date ";
echo $date;
echo " ";
echo "date_number ";
echo $date_number;
echo " ";
echo "launchdate ";
echo $launchdate_number;
echo " ";
echo "days_since_launch ";
echo " ";
echo $days_since_launch;
echo "<br>";
$fileHandle = fopen("sitemap.csv", "r");
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
if ($row[0] > $days_since_launch) continue; // display only pages were value in 1st column[0]less that $days_since_launch
//Print out my column data - exclude 1st column[0]
echo 'Loc: ' . $row[1] . '<br>';
echo 'Lastmod: ' . $date . '<br>';
echo 'changefreq: ' . $row[2] . '<br>';
echo 'priority: ' . $row[3] . '<br>';
echo '<br>';
}
fclose($file_handle);
?>
After many hours I managed to find a solution which reads a CSV file and echos a valid xml sitemap. Thanks to sources in comments of code.
<?php
//Sources for this solution
// https://thisinterestsme.com/reading-csv-file-with-php/
// https://stackoverflow.com/questions/40285479/filtering-and-displaying-a-csv-file-with-php
// https://www.webslesson.info/2017/06/make-dynamic-xml-sitemap-in-php-script.html
header("Content-Type: application/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>';
$date = date("Y-m-d"); // Todays Date
$date_number = strtotime($date); // Todays date as Integer
$launchdate_number = strtotime('2020-02-09'); //Launch Date as Integer 1581206400
$days_since_launch = ($date_number - $launchdate_number) / 86400; // Days since Launch date
// Echo data for testing, will not be in the final XML file
$fileHandle = fopen("sitemap.csv", "r");
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
if ($row[0] > $days_since_launch) continue; // display only pages were value in 1st column[0]less that $days_since_launch
//Print out my column data - exclude 1st column[0]
echo '<url>' . PHP_EOL;
echo '<loc>'. $row[1] .'</loc>' . PHP_EOL;
echo '<lastmod>'.$date.'</lastmod>' . PHP_EOL;
echo '<changefreq>'. $row[3] .'</changefreq>' . PHP_EOL;
echo '<priority>'. $row[4] .'</priority>' . PHP_EOL;
echo '</url>' . PHP_EOL;
}
echo '</urlset>';
?>
My goal is to use PHP to read data from a text file and display a page based on said data.
The text file would look something like this...
joe smith|ceo|chief executive officer|10|14|126
Jane Doe|cfo|chief financial officer|8|12|94
What I need to be able to do is read the text file, extract each of the values, separated by the "|" token, and format the output in a table-like display. When reading the text file, the first column (name) equates to a picture, located in a subfolder. Therefore, the output should look something like this...
Can anyone out there assist with this request?
Thanks in advance.
You need something like that:
I would save the Data in this example in a file called test.csv
But I think you get some problems with the first row. A Space in the src of the img-Tag....
I would replace the space from the Name with str_replace() in the PHP
and the space in the name of the Pictures with Underscrore "_"
<?php
echo '<table>';
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !==false) {
$num = count($data);
//print_r($data);
echo "<tr> ";
$row++;
for ($c=0; $c <= $num; $c++) {
if ($c==0){
echo '<td><img src="YOUR/SUBFOLDER/"'.$data[$c]
."/>".$data[$c].'</td>';
}else{
echo '<td>'.$data[$c] .'</td>';
}
}
echo "</tr> \n";
}
fclose($handle);
echo '</table>';
}
?>
Hope It Helps :-).
Sorry for my bad english
I have a database and PHP file which outputs a module catogaries by the year the module was taken in. accompanying this is how much the module is worth.. eg Computer Science 10. The output on the screen needs to have the TOTAL of the points within that YEAR
So it looks like this:
2001/02
cs 10
bi 10
chem 10
total 30
This is all fine and works APART from if there is more years like this:
2001/02 0 points
2002/03 120 points
2003/04 120 points
But there is points in 2001/02 but the code seems to overwrite this before outputting it.
Here is the PHP code:
$points = array();
while ($row = mysql_fetch_array($result)) {
if ($year != $row["ayr"]) {
echo "<tr><th colspan='3'><b>" . $row["ayr"] . "</b></th></tr>";
$year = $row["ayr"];
echo "<td align='right'><b> Total Module Points: ".array_sum($points)."<td></b>";
$points = array();
}
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
echo "<tr>";
echo "<td>" . $row["mid"] . "</td>";
echo "<td>" . $row["mtitle"] . "</td>";
echo "<td>" . $row["credits"] . "</td>";
echo "<tr>";
if ($year != $row["ayr"]) {
echo "<td align='right'> Total Module Points: ".array_sum($points)."<td>";
}
}
So the code gets the student number, output each module by year and then adds up the module points and gives a total but I cannot get the first table to work
regards
Maybe this causes your problem?
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
Basically, $year will always be equal to $row["ayr"], is this a desired behavior?
The 'equal' comparison operator is '==' as stated before.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So I get the following error.
[02-Nov-2015 16:29:48 America/Los_Angeles] PHP Warning:
number_format() expects parameter 1 to be double, string given in
C:\inetpub\wwwroot\handpaytest\index.php on line 17
This the code that its complaining about.
echo "<td>Past Week: $" . number_format(htmlspecialchars($cell)) . "</td>";
In context
<div id='Title'></div>
<div id='week'>
<?php
echo "<center><table>\n\n";
$f = fopen("week.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>Past Week: $" . number_format(htmlspecialchars($cell)) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</center></table>";
?>
</div>
What htmlspecialchars does is Convert special characters to HTML entities
So, you need to Type caste $cell as (float)$cell before passing it to
number_format
number_format((float)$cell)
As we don't know what $cell contains, You can try to force its type to be float.
echo "<td>Past Week: $" . number_format((float)$cell)) . "</td>";