Here is my code mixed PHP and HTML.
(It shows 4X4 table.)
How can u make this code to get more readability?
If u change HTML indentation, U should change whole HTML.
(This code is part of whole source.)
Do u have any idea for me. Please let me know. Ta.
<!-- GALLERY BEGIN -->
<tr>
<td style="padding-top:5px;"><table width="100%" border="0" cellpadding="2" cellspacing="0">
<tr>
<?php
$ii = 0;
$aRows = getArticle('board_table', $DB_CONNECT, 8);
foreach ($aRows as $iidx => $aRow) :
$ii++;
$U = getUpfiles('upload_table',$aRow[uid],'');
$pic = getImage($U);
?>
<td width="75"><table width="60" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><img src="<?=$pic?>"/></td>
</tr>
<tr>
<td align="center"><?=getStrCut($aRow[subject], 8, '..')?></td>
</tr>
</table></td>
<?php if($ii%4==0): ?>
</tr>
</table></td>
</tr>
<tr>
<td><table width="100%" border="0" cellpadding="2" cellspacing="0">
<tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table></td>
</tr>
<!-- END BEGIN -->
I would suggest using some kind of templating engine. Like smarty. That will allow you to keep your design en data more seperate.
Don't even bother about the HTML indentation, it doesn't matter the least bit. Neither to your users, nor to your browser and for your debugging, you should use something like the Developer Tools from Chrome or good ol' Firebug - Those tools indent your HTML for you, no matter what the actual codebase looks like.
Indent the way you can read the code best, and not what you think is best for the program. As for that, you should really avoid mixing HTML and PHP at all. As bkwint already said, use templating engines like SMARTY or TWIG. Although, with them you still have some weird "in-between" code in your HTML, but it will look much cleaner and easier to understand.
As for your current code: Go with the standard indentation, no matter if you are in a PHP code block or in the HTML parts. That means, indent when opening a loop, an if or a tag. This should at least somehow clean up that table-driven-madness you have going there.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm fairly new to PHP and have a few questions.
What I'm not sure of is how I should structure or implement PHP code into the HTML.
So far, I have structured the coding in two different ways, either echoing out the HTML or keep the PHP as minimal as possible.
What of the two following examples would you prefer? I guess most would answer code number one, but why? Is it because of the abillity to read the HTML syntax highlights?
As you can see in code number one I have to type the PHP start and end tags for just ending the foreach function, which is a bit annoying when the code starts to get really big. Looks like the code is full of start and end PHP tags for the smallest operation.
How do you structure your code?
Code example 1:
<table border="5">
<?php
foreach ($a3 as $nokkel => $verdi){
?>
<tr>
<td><?php echo $nokkel; ?></td>
<td><?php echo $verdi['selskap']; ?></td>
<td><?php echo $verdi['siste']; ?></td>
</tr>
<?php } ?>
</table>
Code example 2:
<table border="5">
<?php
foreach ($a3 as $nokkel => $verdi){
echo "<tr>";
echo "<td>$nokkel</td>";
echo "<td>$verdi['selskap']</td>";
echo "<td>$verdi['siste']</td>";
echo "</tr>";
}
?>
</table>
Both examples are good. But i usually prefer example 2.
But in minimal coding like this ( No need to echo again and again ):
<table border="5">
<?php
foreach ($a3 as $nokkel => $verdi){
echo '<tr>
<td>'.$nokkel.'</td>
<td>'.$verdi['selskap'].'</td>
<td>'.$verdi['siste'].'</td>
</tr>';
}
?>
</table>
It depends on how much HTML content and PHP variables, you have on the page.
Considering your example, it's a simple table, with just values to be displayed. <%= $some_value %> vs echo "$some_value" isn't much of a difference.
But incase of complex HTML pages, where there's a lot of content, I believe the Example 1, is going to come in handy. Embedding PHP here and there instead of echoing the content, is more convenient, readable and future editable.
This question and the answers will be highly opinionated, since you're asking what people prefer.
However, I'd like to point out that php does support a different syntax than the one you're using, namely foreach:/endforeach if/endif, etc. This way, your example
<table border="5">
<?php
foreach ($a3 as $nokkel => $verdi){
?>
<tr>
<td><?php echo $nokkel; ?></td>
<td><?php echo $verdi['selskap']; ?></td>
<td><?php echo $verdi['siste']; ?></td>
</tr>
<?php } ?>
</table>
could be better written like this:
<table border="5">
<?php foreach ($a3 as $nokkel => $verdi): ?>
<tr>
<td><?php echo $nokkel; ?></td>
<td><?php echo $verdi['selskap']; ?></td>
<td><?php echo $verdi['siste']; ?></td>
</tr>
<?php endforeach; ?>
</table>
This has several added benefits:
it's more compact (wastes fewer lines)
it's easier to follow several block levels (think if's inside if's inside foreach's)
it's easier to read
you keep indentation in your code. This is important, since with your echo suggestion, you quickly lose a good overview of which html indentation level you are on.
Syntax highlighting will still be applied in all your examples if you have a decent IDE, so that shouldn't be a major concern.
Edit: Added a link to the php manual for the alternate control syntax.
Edit 2: Since we're into the topic of alternate syntaxes, you can also utilize the "short echo" syntax to further reduce the verbosity of your code, by changing your <?php echo to <?=. Short echo is always available if you're using php version 5.4 or later (which you should most definitely do if you're starting to learn or use php now).
Using this, your code could be further refactored into this:
<table border="5">
<?php foreach ($a3 as $nokkel => $verdi): ?>
<tr>
<td><?= $nokkel; ?></td>
<td><?= $verdi['selskap']; ?></td>
<td><?= $verdi['siste']; ?></td>
</tr>
<?php endforeach; ?>
</table>
The two examples are okay and it really depends on the developer which one he/she thinks has better readability. But whatever you choose, there are always trade offs like for example:
for example 1, you still have to type lots of php starting and ending tags. While for example 2, you still have to write php tags once though with every html tags must be inside an echo. But for me, Option 1 has more readability for me than the second one so I choose option 1.
Generally when following the Model-View-Controller pattern, which is often done in web applications now-a-days, developers try to keep as much logic as possible outside the HTML generation.
That's why most web development frameworks use a template engine, which lead to code much closer to your first example. Aside from the advantages you and the others mentioned such as clearer syntax, one big advantage is that these engines make sure that the output is cleanly escaped. In pure PHP you have to remember to use htmlspecialchars making the code even longer - and if you forget it can result in dangerous security holes.
So my advice is: Don't use either syntax. Instead look for a template engine to use instead.
<table width="100%" cellspacing="1" cellpadding="0" border="1">
<tbody>
<tr>
<td height="30" bgcolor="#006699" align="center" class="heading" colspan="6" style="color:#fff; font-size:22px;">hello this is test</td>
</tr>
<table width="\\100%\\" cellspacing=\\"1\\" cellpadding=\\"0\\" border=\\"1\\">
<tbody>
<tr>
<td height=\\"30\\" bgcolor=\\"#006699\\" align=\\"center\\" style=\\"color:#fff; font-size:22px;\\" colspan=\\"3\\" class=\\"heading\\">hello this is test </td>
</tr></tbody></table>
Is it possible that i can just remove the backslashes, from this?
Your server has Magic Quotes enabled. You can contact your host and ask them to disable it, or before you send the data to your query you can use stripslashes() on it. See this answer for more info.
In your host probably has magic_quotes_runtime turned on.
You can turn it off with set_magic_quotes_runtime(0).
Please turn off magic_quotes_runtime, and then change your code to use bind variables, rather than using the string escaping If you are using mysql_real_escape_string .
To make sure there are no slashes in that value, you can apply
echo "Magic quotes is " . (get_magic_quotes_gpc() ? "ON" : "OFF");
Or you can perform a .htaccess edit to turn off magic_quotes, add the following line in your .htaccess file
php_flag magic_quotes off
I am using Behat and am trying to select some form elements.
My HTML is as follows - Basically I have two required fields, one an input and one a textarea, and a checkbox.
<table class="table">
<thead>
<tr>
<th>Delete</th>
<th>Question</th>
<th>Reference</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="delete" /></td>
<td><textarea name="question" required="required"></textarea></td>
<td><input type="text" required="required" name="reference" /></td>
</tr>
</tbody>
</table>
My xpath selector that gets the form elements is:
//table/tbody/tr/td/input
And this works fine for inputs obviously - but when I added the textarea and tried to check it, it can't find the textarea, because duh, it's not an input.
I tried this: //table/tbody/tr/td/(input or textarea) and several variations of using "or", |, etc. I can't figure out how to specify multiple types of elements to try to match.
Thanks In Advance! :)
PHP's XPath Processor only supports XPath 1.0, which does not allow alternations in path steps. A valid XPath 2.0 expression would have been
//table/tbody/tr/td/(input, textarea)
XPath 1.0 requires you to either provide full paths like this:
//table/tbody/tr/td/input | //table/tbody/tr/td/textarea
or use a predicate with name-test while using the wildcard node test:
//table/tbody/tr/td/*[local-name() = 'input' or local-name() = 'textarea']
The latter version will be probably preferable regarding performance as the XML file will only be scanned once.
Untested in Behat/PHP, but this is how it would look if following the XPath syntax.
//table/tbody/tr/td/input | //table/tbody/tr/td/textarea
I dont mean to be a bother and I know this has been asked a thousand times before but i'm just not understanding the concept. I was wondering if somebody could walk me through it, Here is what i'm trying to do:
I have a set of information inside an html file. The file is uploaded to the server and i need to parse information out of the file inside of set parameters (demo code to follow). I have been reading on parsing for over a week and understand some of it but just not grasping the concept, i guess i just need somebody to do one on this demo for me to understand and if you could, break down the search variables please. Here's the demo:
<hr>
<a id="Operating_System"></a>
<table WIDTH="100%" BORDER="0" CELLSPACING="0" ALIGN="CENTER">
<CAPTION ALIGN="TOP"><FONT size="5">Operating System</FONT></CAPTION>
<tr><td>Top</td></tr>
<TR ALIGN="LEFT" BGCOLOR="#00FF00">
<TH>Property</TH>
<TH>Value</TH>
</TR>
<TR BGCOLOR="#F0F0F0">
<TD>Name</TD>
<TD>Windows 7 Professional x64 Service Pack 1</TD>
</TR>
<TR>
<TD>Features</TD>
<TD>Terminal Services in Remote Admin Mode, 64 Bit Edition, Media Center Edition, Multiprocessor Free</TD>
</TR>
<TR BGCOLOR="#F0F0F0">
<TD>Up Time</TD>
<TD>5 Days 22 Hours 4 Minutes 26 seconds</TD>
</TR>
<!-- Operating System Duration: 1.853 seconds -->
</table>
<hr>
<a id="Installed_Updates"></a>
<table WIDTH="100%" BORDER="0" CELLSPACING="0" ALIGN="CENTER">
<CAPTION ALIGN="TOP"><FONT size="5">Installed Updates</FONT></CAPTION>
and here is what i'm trying to accomplish. On this demo, i would need the information parsed but only certain information to come back. there is a lot more information here but only need about 30 things total on each document. first i need to search from Operating_System to Installed_Updates, this will give me the first set area i need to gather information (there is other groups too so i'll make one for each group of information). The i need to make the search more specific such as from <TR> to </TR> which will give me the actual information set i need. After that just grap the first 'name' and 'value' to store in a database.
Again, i know it's out there but i'm just not getting the whole concept of simple expressions. After i do it a few times on an actual document, i'll get the hang of it i think.
Thank you all so much for the help, i really appreciate it.
This only works for fixed HTML with little variations. But if you just want a simple example, here is one:
preg_match('#<TD>Up Time</TD>.*?<TD>([\w ]+)</TD>#is', $html, $match);
print $match[1]; # ^^^^^^
See also https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world for some tools. And http://regular-expressions.info/ to learn the syntax.
But as said, if you want to extract a lot of values, there are easier options.
Consider the following example:
<table>
<tr>
<td>Row One</td>
</tr>
<?php
if ($rowtwo)
{
?>
<tr>
<td>Row Two</td>
</tr>
<?php
}
?>
</table>
If $rowtwo is true, the second row is output, otherwise it is skipped.
The code works as desired, however I am evaluating Netbeans (7 beta) as a PHP IDE (instead of just using a text editor). Netbeans flags the code with an error:
Misplaced non-space characters insided
[sic] a table.
Should I consider an alternate way of writing this code, or is Netbeans incapable of understanding this flow control wrapper for HTML output?
Edit
The example does not show the indentation I originally used, however various methods of indentation do not affect Netbeans in flagging it as an error.
Removing whitespace prior to the <?php and ?> tags as well as using endif; instead of curly braces both result in the same functionality, but are still flagged.
I think this is a problem and/or weak point with Netbeans' code parsing.
One of the advantages of PHP is being able to insert PHP code fragments right in your HTML. Your code above is fine. Alternatively, you can do it like this, but both are exactly the same.
<table>
<tr>
<td>Row One</td>
</tr>
<?php
if($rowtwo) {
echo "<tr>\n";
echo "\t\t<td>Row Two</td>\n";
echo "\t</tr>\n";
}
?>
</table>
This is pretty typical syntax for presentational views in PHP and other similar languages. It's not elegant, and it's likely to confuse IDEs, but it's not generally considered bad practice.
Your code is valid php. Netbeans may be trying to validate it as HTML, but I don't know much about netbeans.
A couple suggestions:
don't put white-space before php opening tags (<?php) it makes it easier to scan a file and see where the php blocks are located
use the if (...): endif; blocks for HTML content:
I.E.:
<table>
<tr>
<td>Row One</td>
</tr>
<?php if ($rowtwo): ?>
<tr>
<td>Row Two</td>
</tr>
<?php endif; ?>
</table>
it helps so you can see where the if statement ends, rather than trying to determine which closing bracket is which. you can also do this for other control structures.
Edit for more details:
I break out of my html indentation with my php indentation. A next level block would look something like this:
<table>
<tr>
<td>Row One</td>
</tr>
<?php if ($rowtwo): ?>
<tr>
<td>Row Two</td>
</tr>
<?php if ($condition): ?>
<tr>
<td>More Content</td>
</tr>
<?php endif; ?>
<tr>
<td>Even more content</td>
</tr>
<?php endif; ?>
</table>
I should also mention that my body element is indented one level, so I rarely ever have html that is flush against my php tags. Often it's more like:
<table>
<?php if ($condition): ?>
<tr><td></td></tr>
<?php endif; ?>
</table>
Which helps to make the PHP stand out.
It's almost acceptable by my standards (What I look for in other people's code). The only change I would make is to indent properly so that it's easier to see at a glance what's happening (make your code more readable). For example:
<table>
<tr>
<td>Row One</td>
</tr>
<?php
if ($rowtwo) {
?>
<tr>
<td>Row Two</td>
</tr>
<?php
}
?>
</table>
That way, it's trivial to see where the if construct ends at a glance...
It is not bad practice or wrong to a certain extent.
However, a better practice is to separate your display logic from your business logic. Your IDE is probably assuming this, and therefore is confused with mixed code.
But again, nothing wrong with mixing html/php!