PHP within HTML etiquette [closed] - php

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 9 years ago.
Improve this question
This has been bothering me for quite some time and I want to know what the typical etiquette is when writing PHP code within HTML.
I have the following code:
<?php
$country_list = array("AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria");
echo '<div class="some-class">
<font color="red">Just some text.</font>
<select>';
foreach($country_list as $country_code => $country_name) {
echo '<option value="' . $country_code . '">' . $country_name;
}
echo '</select>
</div>';
?>
This to me looks extremely ugly because of how the HTML isn't lined up and it's hard to work with something that doesn't look good.
Is there any way I can improve so that it looks better? Is there some sort of PHP etiquette when writing PHP code like this inline with HTML?
Thanks.

It's common practice to separate your code that outputs the HTML (the "view") from your logic (typically in a "controller"). At a minimum, this can be done with PHP code that just handles output, but is usually done with a template engine, such as Smarty.
A template engine can be overkill if you have a simple application. In these cases, there are some things you can do to clean up your code:
Disregard HTML indentation. Only worry about your code indentation in PHP. That's where it matters to you anyway. If you need to use indented HTML, let your browser's developer tools worry about it.
Avoid closing/opening PHP tags repeatedly. Just stick to echo. Again, if you need to mix PHP and HTML so much that you feel the need to repeatedly close/open PHP tags, consider a template engine.
Finally, be sure to use htmlspecialchars() around any arbitrary data you output into HTML to ensure that you are generating valid HTML, and avoiding certain kinds of XSS attack vulnerabilities.

This is all pretty subjective stuff, but you could consider only breaking into PHP when absolutely necessary:
<div class="some-class">
<font color="red">Just some text.</font>
<select>
<?php
$country_list = array("AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria");
foreach ($country_list as $country_code => $country_name) {
printf('<option value="%s">%s</option>', $country_code, $country_name);
}
?>
</select>
</div>
I shall assume your values don't need to be escaped here, i.e. no "naughty countries".
Alternatively, there are template engines that can help you with it, such as PHPTAL:
<div class="some-class">
<font color="red">Just some text.</font>
<select>
<option tal:repeat="country countries" tal:attributes="value repeat/country/key" tal:content="country" />
</select>
</div>
PHP code:
$tal = new PHPTAL('path/to/template');
$tal->set('countries', $countries);
echo $tal->execute();
The nice thing here is that everything stays in HTML mode and you've separated display logic (how to show data) from business logic (how to generate it).

this is what I usually do
<?php
$country_list = array("AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria");
$countries = '';
foreach($country_list as $country_code => $country_name) {
$countries. = '<option value="' . $country_code . '">' . $country_name;
}
?>
//html part
div class="some-class">
<font color="red">Just some text.</font>
<select name="country>
<?php echo $countries; ?>
</select>
</div

You could do something like this... I do it sometimes
<?php
$country_list = array("AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria");
?>
<div class="some-class">
<font color="red">Just some text.</font>
<select>
<?php foreach($country_list as $country_code => $country_name) { ?>
<option value="<?=$country_code?>"><?=$country_name?></option>
<?php } ?>
<select>
</div>

Not sure about "etiquette" but echoing HTML may not be the best idea. Maybe something like this:
<div class="some-class">
Just some text
<select>
<?php
foreach($country_list as $country_code => $country_name) {
?>
<option value="<?php echo $country_code;?>">
<?php echo $country_name; ?>
</option>
<?php
}
?>
</select>
</div>
So minimize echoing HTML tags.

Related

Which is the better way to insert HTML tags into PHP code?

I see two methods but I don't know which is better, should I insert a div tag like this :
echo "<div>";
or like this ?
?> <div> <?php
There's no right answer to this.
When displaying a lot of HTML, I normally use ?> <div> <?php. This is especially true for when looping over data from a database, I would use:
<?php while ($row == $query->fetchObject() ) : ?>
<div class="row-<?php echo $row->id ?>">
//Some more of the data
</div>
<? endwhile; ?>
However, displaying only a little, I normally just echo it.
<?php echo "Hello, my name is <strong>Joe Doe<strong>"; ?>
I would encourage you to play with it and find what you like best.
The text editor i am using has the color formatting, when you are echoing things, it only all comes out the same color, so if you are outside of PHP you get the benefit of the color co-ordination.

Placeholders added to via a str_replace

I am trying to make a placeholder for forms in concrete5 using a the tablelessforms addon.
So far I have enabled the form to produce placeholders for inputs using the below code. However, the textarea while displaying, the function str_replace does not replace and add my placeholder.
Here is the code below and a link to the site : http://79.170.44.138/holidayletmidwales.co.uk/newsite/
<div class="fields">
<?php foreach ($questions as $question): ?>
<div class="field field-<?php echo $question['type']; ?>">
<?php if ($question['textarea']) {
$question['textarea'] = str_replace('rows="3"', 'rows="3" placeholder="'.$question['question'].'"', $question['textarea']);
echo $question['textarea'];
} else {
$question['input'] = str_replace('value=""', 'value="" placeholder="'.$question['question'].'"', $question['input']);
echo $question['input'];
} ?>
</div>
<?php endforeach; ?>
</div><!-- .fields -->
Any help would be greatly appreciated.
The find and replace isn't working as you're searching for rows="3" when the markup has rows="5". A better option, rather than searching for an attribute which could change, would be to find the beginning of the tag, e.g. str_replace ('<input', '<input placeholder="foo"', $html) or, if possible, to extend the class generating the tags to handle placeholders as you require.

How to use if-else in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to use selected option with condition. if $type is room then bed will be selected and if it is bathroom then toilet will be selected. what is wrong with this code. how to correct it????
<html>
<body>
<?php
$type="bathroom";
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<select name="bedtype">
<% if($type=="bathroom"){ %>
<option value="room">BED</option>
<option value="bathroom" selected>TOILET</option>
<% } else { %>
<option value="room" selected>BED</option>
<option value="bathroom" >TOILET</option>
<% } %>
</select>
</form>
</body>
</html>
You are mixing ASP and PHP tags.
While ASP tags were allowed in PHP 5, as of PHP 7, they have been deprecated and removed. You should switch to strictly <?php ?> and <?= ?>.
http://php.net/manual/en/language.basic-syntax.phptags.php
You also have $_SERVER['PHP_SELF'] wrong.
Ternary conditionals would simplify the code greatly. They are in the form if true statement ? do truth : do falsehood. Providing an echo statement before the ternary conditional would echo out the true or false result.
<html>
<body>
<?php $type = "bathroom"; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="bedtype">
<option value="room" <?php echo $type == "room" ? 'selected' : ''; ?>>BED</option>
<option value="bathroom" <?php echo $type == "bathroom" ? 'selected' : '' ?>>TOILET</option>
</select>
</form>
</body>
</html>
Your code is correct in PHP < 7.0.
You use optional ASP tags ( <% (...) %> ) to embed PHP code.
To activate it, you have to modify your php.ini file turning this line:
asp_tags = Off
in:
asp_tags = On
Please note that ASP tags are rarely used and completely removed on PHP 7.0.
To avoid future incompatibility issue, use standard php tags <?php (...) ?>
As alternative, to echo something, you can use short tags <?= (...) ?>.
So, this:
<?php echo 'Hello World'; ?>
is the same as:
<?= 'Hello World'; ?>
or (you can omit closing semicolon):
<?= 'Hello World' ?>
For the records, there is another short-tag style ( <? (...) ?> ) that must be enabled in php.ini. However, the use of this short-tag is discouraged and substantially abandoned (this style is primary used to identify XML).

PHP syntax alternatives? [closed]

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 9 years ago.
Improve this question
Are there any way to use this alternative syntax?
<div class="lines-rates">
<?php foreach($info as $k => $v){ echo : ?>
<div><span>{$k}</span>{$v}</div><?php ; } ?>
</div><!-- #lines -->
I mean:
<?php echo : ?><p>this is your {$username} And this html code could be more than one line and sure other html elements also</p><?php endecho; ?>
So we can easily see html code.
I want to have html inside PHP. Not PHP inside html.
<?php echo '<p>this is your '.$username.' And this html code could be more than one line and sure other html elements also</p>'; ?>
It's definitely not the way that I want.
I'm using
<?php if($info) : ?>
<div class="lines-rates">
<?php foreach($info as $k => $v){ echo "<div><span>{$k}</span>{$v}</div>"; } ?>
</div><!-- #lines -->
<?php endif; ?>
I do not want to use html inside php.. Like
<?php echo "<div><span>{$k}</span>{$v}</div>";?>
Also following line is possible but this is too verbose for me - is it not? Why do I have to write <?php echo $k; ?> to echo simple variable?
<?php $if($info) : ?>
<h2>Weekly Charter Rates </h2>
<div class="lines-rates">
<?php foreach($info as $k => $v) : ?>
<div><span><?php echo $k; ?></span><?php echo $k; ?></div>
<?php endforeach; ?>
</div><!-- #lines -->
<?php endif; ?>
I need clean and pure code as much as possible.
This type of writing again fails.
<?php foreach($info as $k => $v) : echo <<<EOT ?>
<p>this is your {$username}</p>
...
some more html
..<div><span>$k</span>$k</div>
<?php EOT; ?>
<?php endforeach; ?>
It was almost best way.
Use this:
<div class="lines-rates">
<?php foreach($info as $k => $v){?>
<div><span><?php echo $k; ?></span><?php echo $v; ?></div>
<?php } ?>
</div>
If you are using only two variable of PHP then no need to echo whole line, just echo those variables.
You can use Heredoc syntax
echo <<<EOT
<p>this is your {$username}</p>
...
some more html
..
EOT;
UPDATE
there must be no other content in the line of second "EOT". Quote from link I've given:
It is very important to note that the line with the closing identifier
must contain no other characters, except possibly a semicolon (;).
UPDATE 2
Change
<?php EOT; ?>
to
<?php
EOT;
?>
DO NOT IDENT SECOND LINE
You could use a templating language such as Twig. Example syntax:
<ul id="navigation">
{% for item in navigation %}
<li>{{ item.caption }}</li>
{% endfor %}
</ul>
what about this
<?php echo '<p>this is your '.$username.' And this html code could be more than one line and sure other html elements also</p>'; ?>
If you're feeling really adventurous you can choose to enable short tags, but both Heredoc and templating engines like Twig mentioned above would be a better idea.
<p>this is your <?=$username;?> And this html code could be more than one line and sure other html elements also</p>
You can also make use of nowdoc
echo <<<'END_OF_HTML'
$hello this is {$a->test}
END_OF_HTML;
OUTPUT:
$hello this is {$a->test}

How can I use an associative array inside an <<<_END html tag?

I'm building my own little blogging platform as a practice/fun/exercise in PHP and MySQL. I'm currently using the following code to output the proper formatting (which works perfectly):
$rows=mysql_num_rows($postsresult);
for ($j=0 ; $j < $rows ; ++$j){
$row=mysql_fetch_row($postsresult);
echo <<<_END
<div class="titlebox"> $row[3] </div>
<div class="maincontent"> $row[2]
<div class="postclosercontainer">
<div class="postcloser">Sincerely, <br />
Samuel'<span>Explosion Festival</span>' Shenaniganfest </div>
</div></div>
_END;
}
However, I found that the while($info=mysql_fetch_array($postsresult){ would be easier to code for, as the data is stored by name instead of by array number (which, with any more than a few fields, becomes aggravating to remember).
I tried to update the code with the prior while loop, but found that when I went to pull the data from the array by name, it no longer functioned properly within the <<<_END tags.
For example: <div class="titlebox"> $data['title'] generates an error.
Is there any way to accomplish this within the <<<_END tags, or should I just use the print function for each line? On a another note, is this even proper coding technique? (I'm only an amateur.)
Better is to directly write HTML. This makes it easier to maintain your HTML and you might be able to use features from your IDE such as syntax highlighting or code completion.
Example:
<?php
// your other code
?>
<?php while(($info=mysql_fetch_array($postsresult))): ?>
<div class="titlebox"><?php echo $info['title']; ?> </div>
<div class="maincontent">
<?php echo $info['content']; ?>
<div class="postclosercontainer">
<div class="postcloser">Sincerely, <br />
Samuel'<span>Explosion Festival</span>' Shenaniganfest
</div>
</div>
</div>
<?php endwhile; ?>
I'm using the alternative syntax for control structures. It increases readability when dealing with HTML, especially if you have nested control structures (brackets are much more difficult to spot when embedded in HTML).

Categories