Force PHP newline to respect current indentation level - php

I have been googling like crazy to find an answer to what I thought would have been a very common question to no avail...
I am using "\n" to break a table into a more readable structure when viewing source. Is there any way to get it to respect current indentation levels? For example:
Turn this:
<table>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
Into this:
<table>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
I am printing the tbody rows and cells out with the following code:
<?php
$first = true;
foreach ($data->rows as $row) {
if ($first) {
print "<tr class='highlight'>";
$first = false;
} else {
print "<tr>";
}
foreach ($row as $cell) {
print "<td>";
printf('%s', $cell);
print "</td>\n";
}
print "</tr>\n";
}
?>

<?php
$first = true;
foreach ($data->rows as $row) {
if ($first) {
echo "\t\t<tr class='highlight'>";
$first = false;
} else {
print "\t\t<tr>";
}
foreach ($row as $cell) {
print "\t\t\t<td>";
printf("\t\t\t\t%s", $cell);
print "</td>\n";
}
print "\t\t</tr>\n";
}
?>
I recommend you to write an identation counter, if you would like to do it dynamically. And remember to use double quotes for escape sequences, single quotes won´t work here (because it´s treated like a variable).

This is what google gave me.
You should concatinate the entire table in one php string, parse it through the function that can be found here:
http://www.daveperrett.com/articles/2007/04/05/format-xml-with-php/
and then simply echo $xml;
I just found it, I give no guarantee that this works as itended but it looks reliable.

The final HTML source have not to respect an indentation... Nobody see it (or you but don't get crazy with this).
Ok, sometimes this is also an obsession for me (one among many others ?), so you can do:
echo '
<tr>';
//Loop starts
echo '
<td></td>';
// Loop ends
echo '
</tr>';
Here you get a newline and your HTML indentation is independant from the PHP one.
Is it what you would ?

Related

php mysql display table

I am a beginner and somehow made to get the query (php & Mysql) I want and using echo i got the output as few lines without difficulty. But now I want the output inside the cell of a table. I tried something like this:
This does not work:
<tr>
<th>subject</th>
<th>grade</th>
</tr>";
echo "<tr>";
echo "<td>".$Row['name1']."</td>;
echo "<td>".$Row['subject1'].</td>";
echo "</tr>";
echo "</table>";
Whereas this work:
echo $line['name1']."<tr></td>"."";
echo $line['subject1']."<tr></td>"."";
The echo $line statement echoes the value of name1 and subject1 without any difficulty. but the echo Row is not showing the output. As my data has only one row I dont have to use any loop. I actually want two fields in first row (name1 and subject1) and then in next row the fields of name2 and subject2 and till name7, subject7. It looks like the format inside the table is wrong. Could someone help me plz?
First of all replace
echo "<td>".$Row['name1']."</td>;
with
echo "<td>".$Row['name1']."</td>";
you are missing (") at the end before (;)
Updated with the missing table tag. Try this
<?php
echo '<table>';
echo '<tr>';
echo '<th>subject</th>';
echo '<th>grade</th>';
echo '</tr>';
echo "<tr>";
echo "<td>".$Row['name1']."</td>";
echo "<td>".$Row['subject1']."</td>";
echo "</tr>";
echo "</table>";
?>
Just to expand the current answers, I'd suggest you use a single echo and concatenate the strings or even better, just use one single string and concatenate only the necessary variables:
<?php
echo '
<table>
<tr>
<th>subject</th>
<th>grade</th>
</tr>
<tr>
<td>'.$Row['name1'].'</td>
<td>'.$Row['subject1'].'</td>
</tr>
</table>';
?>
This of course works better if the amount of PHP code is greater than the amount of HTML code. But if you were to write more HTML than PHP, it'd make more sense to just open and close <?php?> tags and echoing the variable you want.
I used an answer instead of a comment for the sake of the example. Feel free to try this approach when you are dealing with several html elements and need to insert your values within them.

I want do style tables, but it doesn't work in PHP

I want to create a site, which displays a lot of records from a database. To make it more reader-friendly, I want to use a styling. One record is white background, the next blue, the next hhite again.
So I tried this:
<?php while ($info = mysql_fetch_array($data)){
PRINT "<tr>";
PRINT "<td>" .$info['articlenr']. "</td>";
PRINT "<td>" .$info['stock']. "</td>";
PRINT "</tr>";
PRINT "<tr>";
PRINT "<td bgcolor=#0066FF>" .$info['articlenr']. "</td>";
PRINT "<td bgcolor=#0066FF>" .$info['stock']. "</td>";
PRINT "</tr>";
}
?>
This works for the view, but the problem is, the blue record is the same as the white, not the next one, it just doubles the record and make it another color.
How can I do this right?
Use :nth-of-type(even) to get even/odd combination of color's.
Here is a demo example:
html:
<table>
<tr><td>item1</td>
</tr>
<tr><td>item2</td>
</tr>
<tr><td>item3</td>
</tr>
<tr><td>item4</td>
</tr>
</table>
css:
tr:nth-of-type(even) { background-color: #0066FF; }
Demo
If you want to do this in PHP, you could do it like this :
<?php
$iter = 0;
$color1 = 'red'; //can se hex code too, like #0066FF;
$color2 = 'blue';
while ($info = mysql_fetch_array($data))
{
echo '<tr style="background-color:'.( ($iter%2==0) ? $color1 : $color2).';">';
// rest of the printing stuff
$iter++;
}
?>
Statement
($iter%2==0) ? $color1 : $color2
does this : it asks the question whether iterator (or row number) is even. If yes, the it takes color1. If not (row is uneven) it takes the second color.
PHP Smarty is good for doing this kind of stuff (iterating over colors and styles), but it may be difficult for beginners.
Please go through this links:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started
http://css-tricks.com/complete-guide-table-element/
Including CSS in .php file
Can I offer some advice on your code? Your approach mixes PHP and HTML in a way that makes it difficult for your development environment to parse your HTML, and you can achieve the same with less keystrokes! Consider this approach instead:
<?php while ($info = mysql_fetch_array($data)): ?>
<tr>
<td><?php echo $info['articlenr'] ?></td>
<td><?php echo $info['stock'] ?></td>
</tr>
<?php endwhile ?>
Changes I've made:
Removed the duplicate row
Rendered everything in HTML mode, and opened PHP tags just for PHP code
Switched the loop to the colon form, which is often thought to be clearer in templates. Do carry on using the brace approach, however, in large chunks of code (e.g. classes)
Written PHP keywords in lower case
Used echo rather than print
Combine this with Joke_Sense10's answer for a full solution.

Kraken API with a PHP script causes HTML page to go blank

Does anyone see a problem with this HTML/PHP code? as soon as i added it, the page showed as blank, with the browser not reading any source code at all. Even if i comment it out with it still is blank!
<body>
<?php
function getInfo ($a)
{
$online = 'images/streamRing/online.png';
$offline = 'images/streamRing/offline.png';
$size = '20';
$array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($a)), true);
if ($array['stream'] != NULL)
{
$channelTitle = $array['stream']['channel']['display_name'];
$streamTitle = $array['stream']['channel']['status'];
$currentGame = $array['stream']['channel']['game'];
echo "<tr><td class='onlineStatus'><img src='$online' height='$size' width='$size' alt='Online' />Online</td>";
echo "<td>$channelTitle</td><td>$streamTitle</td></tr>";
}
else
{
echo "<tr><td class='onlineStatus'><img src='$offline' height='$size' width='$size' alt='Offline' />Offline</td>";
echo "<td>$a</td><td> </td></tr>";
}
}
?>
.... (later in the page...) ....
<table class="onlineList">
<th>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</th>
<?php
$streamer_1 = 'xxxx';
$streamer_2 = 'yyyy';
getInfo($streamer_2);
getInfo($streamer_1);
?>
</table>
The php code was developed using Kraken API, which is demonstrated rather simply here:
http://www.incendiarymedia.org/twitch/status.php
Edit: I noticed and fixed the breaking error. I used double quotes within a php echo, which is..... bad! However, the code still has an error. The table shows the headers, then the individual cells are misaligned. Somehow the images for the first column show up to the LEFT of the first column header. I don't see why!
Because this is invalid table markup
<table class="onlineList">
<th>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</th>
The <th> element behaves like a cell, but you are using it like a row instead of <tr>
Try this:
<table class="onlineList">
<tr>
<td class="onlineStatus"><h3>Status</h3></td>
<td><h3>Streamer Name</h3></td>
<td><h3>Stream Title</h3></td>
</tr>

Multiple column HTML Table From Single Column Text File In PHP

I have a simple working PHP script to write an HTML table from a text file that contains a single column of data that contains HTML links. This writes the data horizontally in a row across 5 or 6 columns as I want it to. But I am looking to set up a script with a loop that will take this list of data and input it into the table until it finishes the data list, so that I do not have to hard code each table cell individually. Just let the script create each table cell, at 5 or 6 columns across (whichever I need for this specific table), go to the next row, etc., until it runs out of data. The data in the data file will be added to on a regular basis, so the table will not be of a certain fixed length forever. I am using the echo command so that I can add some more HTML formatting later on.
Even though my existing script is simple and it works, if you can think of a better way of doing what I am trying to do, all suggestions are appreciated.
Thanks in advance, Stan...
PHP code follows:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) { while (!feof($item)) { $lines[] = fgets($item, 4096); } fclose($item); }
echo'
<TABLE border="1">
<TR>
<TD>'.($lines[1]).'</td>
<TD>'.($lines[2]).'</td>
<TD>'.($lines[3]).'</td>
<TD>'.($lines[4]).'</td>
<TD>'.($lines[5]).'</td>
<TD>'.($lines[6]).'</td>
</tr>
<TR>
<TD>'.($lines[7]).'</td>
<TD>'.($lines[8]).'</td>
<TD>'.($lines[9]).'</td>
<TD>'.($lines[10]).'</td>
<TD>'.($lines[11]).'</td>
<TD>'.($lines[12]).'</td>
</tr>
<!-- And So On, And So On, ETC -->
</table>'
?>
<?php
echo '<table border="1"><tr>';
for($i=0; $i<sizeof($lines); $i++) {
echo '<td>'.$lines[$i].'</td>';
if(($i+1)%6==0 && $i!=sizeof($lines)-1) echo '</tr><tr>';
}
echo '</tr></table>';
?>
Explanation:
Repeats through each "line" and writes the <td>value</td>
If a line is a multiple of 6, after writing the value, then close the row, and open another (unless it's the last one, since it will close the row after the loop as well.
(I assume you meant to start on $line[0], but if you really meant to start on $line[1], just change the $i=0; to $i=1;, remove the +1 in the row check, and change $i<sizeof to $i<=sizeof
$lines = chunk_split($lines,6);
?>
<TABLE border="1">
<? foreach ($lines as $row): ?>
<TR>
<? foreach ($row as $value): ?>
<TD><?=$value?></td>
<? endforeach ?>
<TR>
<? endforeach ?>
</TABLE>
In pseudo code...
x = 0
echo '<TABLE border="1">'
For each $line in $lines {
x = x + 1
if x = 1 {
echo '<TR>'
}
echo <TD>'.($line).'</TD>
if x = 6 {
echo '</TR>'
x = 0
}
}
echo '</TABLE>'
Note the use of the $line object to hold the value of the $line array element.
hth
If you use a loop, you can also avoid reading the complete file into memory, which might be beneficial:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) {
echo'<TABLE border="1">';
$i=0;
$lines=array();
while (!feof($item)) {
$line[] = fgets($item, 4096);
$i++;
if ($i==6) {
echo "<tr>";
echo '<TD>'.($lines[0]).'</td>';
echo '<TD>'.($lines[1]).'</td>';
echo '<TD>'.($lines[2]).'</td>';
echo '<TD>'.($lines[3]).'</td>';
echo '<TD>'.($lines[4]).'</td>';
echo '<TD>'.($lines[5]).'</td>';
echo "<tr>";
$i=0;
$lines=array();
}
}
echo '</table>';
fclose($item);
}
?>

PHP How to replace string literals using a value from an array?

I'm not sure if it's the proper title to use...
Here is my question.
I have stored table field names from a database in an array, and created a string like following
foreach ($fields as $field) {
$str.="<td>{$data[key][field]}</td>";
}
And I have stored the data from the table in a different array which is of the form
$data=array(array('name'=>"name 1",'address'=>"Address One"),array('name'=>"Name 2",'address'=>"Address two"),array('name'=>"Name 3",'address'=>"address three"),array('name'=>"test",'address'=>"test one"));
Now I have done the following
eval("\$str = \"$str\";");
foreach ($data as $key => $souceStr) {
?>
<tr>
<?=$str?>
</tr>
<?
}
?>
My aim is to replace the string that i have created from the first array with the values from the second array. I have seen coding in CMS like joomla where they replace '{somename}' with a value I want to do the same here.
=================================================
I'm sorry My question was not clear. But i got what i was looking for. Here is the code
<table width="100%" cellpadding="0" cellspacing="0" align="center" border="1">
<tr>
<?
foreach ($header as $val) {
?>
<th><?= $val ?></th>
<?
}
?>
</tr>
<?
foreach ($fields as $field) {
$str.='<td>$souceStr['.$field.']</td>';
}
foreach ($data as $key => $souceStr) {
eval("\$eval_str = \"$str\";");
?>
<tr>
<?php echo $eval_str; ?>
</tr>
<?
}
?>
The idea was to print a html table.
I don't think I completely understand what your question is, but what if you simply made a string from the second array just like you did from the first one? the result wold be the same, right?

Categories