PHP loop hanging/interspersed/threaded through HTML - php

I can't figure out how to say what I'm talking about which is a big part of why I'm stuck. In PHP I often see code like this
html
<?php
language construct that uses brackets {
some code;
?>
more html
<?php
some more code;
}
?>
rest of html
Is there any name for this? Having seen this lead me to try it out so here is a concrete example whose behavior doesn't make sense to me
<div id="content">
<ul id="nav">
<?php
$path = 'content';
$dir = dir($path);
while(false !== ($file = $dir->read())) {
if(preg_match('/.+\.txt/i', $file)) {
echo "<li class=\"$file\">$file</li>";
?>
</ul>
<?php
echo "<p class=\"$file\">" . file_get_contents($path . '/' . $file) . '</p>';
}
}
?>
</div>
Which outputs roughly <div><ul><li></li></ul><li></li><p></p>...</div> instead of <div><ul><li></li>...</ul><p></p>...</div>, which is what I thought would happen and what I want to happen. To make it clearer I want the <li> inside the <ul> and the <p> inside the <div>. Yes, I know there is an easy solution but I was wondering if there is a way to do it with the technique I am looking for a name for.

Just something to add here:
If you're using a PHP loop for templating, there is another syntax that helps you avoid confusion with indentation and which-braces-match-which:
<?php
foreach($items as $item):
?>
<b>item: </b> <?php echo $item; ?> <br />
<?php
endforeach;
?>
this may be an oversimplification, but really you shouldn't be using anything more complicated than this in a template. Things like the $items variable and anything else you need should be set up by the code which includes the template, and not in the template itself.

Related

Initializing the hidden input value with PHP [duplicate]

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>

What is the best way to turn a HTML start and end tag into a function?

I have a complex HTML tag, with many attributes and it appears in very different parts of the code.
Example:
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
<some complex html code ... >
</div>
And I do not want to repeat this <div></div> with all its attributes in different parts of the code as it changes quite often during development.
If I create a function like this (example in PHP):
function myDivStart() { ?>
<div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
<?php }
then my resulting code would look like
<?php myDivStart(); ?>
<some html code ... >
</div>
and the finishing </div> would look kind of out-of-place, since there is no visual starting <div>. My text editor would also not parse this correctly and syntax highlighting is messed up.
Then, if I create another function for the closing </div>, it would be a very silly function indeed:
function myDivEnd() { ?>
</div>
<?php }
and turn the original code into
<?php myDivStart(); ?>
<some html code ... >
<?php myDivEnd(); ?>
This would solve the syntax highlighting problem, but it still feels very unclean to have such a silly function to close.
UPDATE: Storing the HTML code in a variable and passing that to a function would not really solve the problem neither, as the HTML inside a variable would not be parsed correctly with syntax highlighting.
$myHTML = 'A very long and complex piece of html';
<?php myDiv($myHTML); ?>
My text editor would not have syntax highlighting there.
And doing the following would also make the code disorderly, as the $myHTML code comes before the <div> and actually, logically belongs after it.
$myHTML = ?>
A very long and complex piece of html
<?php ;
myDiv($myHTML);
Is there any pattern that would solve for this?
If it's always the same tag you can use a variable or a constant instead of a function.
E.g.
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
If you have varying parts of that tag then you can instead indeed make a function, e.g.:
function openingDiv($class) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >"
}
function closingDiv() {
return "</div>";
}
You can also make it a bit more sophisticated:
function wrapContentInDiv($content) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >$content</div>";
}
Example uses:
<?php
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
?>
<leading html>
....
<?php echo $openTag ?>
<some html here>
<?php echo $closeTag ?>
...
<?php echo $openTag ?>
<some other html here>
<?php echo $closeTag ?>
<trailing html>
You can take this one step further and define your code in a separate php file:
e.g. config.php
Then you can:
<?php
require_once("config.php")
?>
...
Update:
You could also use a template e.g. file complexDiv.php
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
Use this as below:
<leading html>
....
<?php //Set any parameters that complexDiv.php needs here
include 'complexDiv.php'
?>
<some html here>
</div>
...
<?php include 'complexDiv.php' ?>
<some other html here>
</div>
<trailing html>
I suspect that before long you'll realise that its worth switching to a template engine like smarty of blade.
It depends on what the some HTML code is but you could do something like this pseudocode
$some_html=''; //your html code goes here as a string
myDiv($some_html);
function myDiv( $arg ){
echo <div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
echo $arg;
echo </div>
}
You can first prepare the HTML on a different file and include that file on the function where the div tags are waiting for them to wrap that content of yours. Hope it helps.
function wrapperDiv() {
$html = '';
$html .= '<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >';
$html .= include_once 'body.php';
$html .= '</div>';
return $html;
}
wrapperDiv();

PHP foreach menu include

Im developing a website and I am trying to a foreach include for my header which includes my navigation menu (the main topic here).
My code inside the header.php file for the navigation menu is here:
<!-- topmenu -->
<div class="menu-header">
<div class="container">
<ul class="top menu">
<?php
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item){
if($item == $title){
echo "<li class='current-menu-ancestor parent'><a href='$item.php'>$item</a></li>";
}else{
echo "<li><a href='$item.php'>$item</a></li>"; }
}
?>
</ul>
</div>
</div>
<!--/ topmenu -->
You may notice that in the code is the condition if($item == $title). In my index.php I have included $title="Home"; which I intended to be taken and used in this if statement.
On my index.php page I have included this with the following code:
<?php
include("header.php");
$title = "Home";
?>
Can anyone tell me where I am going wrong?
Not an answer, but comments aren't suitable for formatted code. You might want to de-duplicate some of your HTML:
$class = '';
if($item == $title) {
$class = ' class"current-menu-ancestor parent"';
}
echo "<li{$class}><a href='$item.php'>$item</a></li>";
Duplicating HTML as you did can lead to maintenance problems later on, if you decide to change something in the menu structure and change only one of the copies of the menu html.
header.php can not look into the future. If you want the variable to be set in the include, you need to set it before:
<?php
$title = "Home";
include("header.php");
?>
So you basically just switched the lines.
Additionally I suggest that you enable error reporting to the highest level when you develop, as it will give you warning on common mistakes that can happen while typing code.
You can do this by adding the following two lines to the top of your script:
error_reporting(~0);
ini_set("display_errors", "1″);
or by changing your PHP configuration.
You need to set $title before including header.php!
i.e.
<?php
$title = "Home";
include("header.php");
?>

How to insert HTML tags in Joomla! module title?

What I'm trying to do is to add some HTML tags to my Joomla! module titles. I will need something like this
Some <b>Title</b>
but when I save !Joomla trims the titles and remove all HTML tags.
I've check the administrator/com_content, which I think should be responsible for inserting the database data, but I couldn't find the answer there.
Can anyone help me with this headache?
Check out ../templates/system/html/modules.php
You can style your module structure in HTML.
function modChrome_myCustomModule($module, &$params, &$attribs)
{
$doc =& JFactory::getDocument();
$css = ".otherClass {}";
$css .= ".yourClass {}";
$doc->addStyleDeclaration($css);
?>
<div>
<?php if ($module->showtitle != 0) : ?>
<h1><?php echo $module->title; ?></h1>
<?php endif; ?> // post your title
</div>
<div>
<?php echo $module->content; ?> // post your module content
</div>
<?php
}
Then call your styled module in index.php:
<jdoc:include type="modules" name="right" style="myCustomModule" />
So I found the solutions. It includes both of the previous answers, so I'm putting a new one here with the correct code.
First of all I need to say, that this solution works only for a fixed amount of words (last one, two, etc.) I need only to have the last one, so I will post an example code with one word.
First as SMacFadyen sad I needed to create a new module structure in my template html folder: /templates/system/html/modules.php file.
Note: If you don't want to add this new module styling to all templates, but just on one of them you need to put the module.php in your template's html folder.
The provided by SMacFadyen looks like this:
function modChrome_myCustomModule($module, &$params, &$attribs)
{
$doc =& JFactory::getDocument();
$css = ".otherClass {}";
$css .= ".yourClass {}";
$doc->addStyleDeclaration($css);
?>
<div>
<?php if ($module->showtitle != 0) : ?>
<h1><?php echo $module->title; ?></h1>
<?php endif; ?> // post your title
</div>
<div>
<?php echo $module->content; ?> // post your module content
</div>
<?php
}
Then expired by the comments of Hanny I've added some php code to match the last word of the title and to store it in a new varibale.The code looks like this:
$wrap_tag = 'b';
$html_title = preg_replace("~\W\w+\s*$~", '<'.$wrap_tag.'>'.'\\0'.'</'.$wrap_tag.'>', $module->title);
Note: the $wrap_tag variable stores the tag you want. You can put b, em, u and etc. to have different result.
The last thing was to replace the displayed title, so I've replaced this code:
<h1><?php echo $module->title; ?></h1>
with this one:
<h1><?php echo $html_title; ?></h1>
The final result was this:
function modChrome_myCustomModule($module, &$params, &$attribs)
{
$doc =& JFactory::getDocument();
$css = ".otherClass {}";
$css .= ".yourClass {}";
$wrap_tag = 'b';
$html_title = preg_replace("~\W\w+\s*$~", '<'.$wrap_tag.'>'.'\\0'.'</'.$wrap_tag.'>', $module->title);
$doc->addStyleDeclaration($css);
?>
<div>
<?php if ($module->showtitle != 0) : ?>
<h1><?php echo $html_title; ?></h1>
<?php endif; ?> // post your title
</div>
<div>
<?php echo $module->content; ?> // post your module content
</div>
<?php
}
Thanks to everybody for the help.
The Gantry framework can help you accomplish what you want (1st word styled one way, 2nd word styled another) - but it's a lot of overhead just accomplish that one task you're looking for. Ultimately you'll have to create a template override for your template, and then do some creative editing with php in order to get it to display that way.
There's no quick and easy way to get that done. You'll have to do some php coding on the backend and edit the template (use an override so you don't hack core files). Ultimately you'll probably have to code the php to pull apart the title, and apply formatting to each pulled apart word (or string of words as the case may be) using CSS.
Hope that helps.

How can I echo HTML in PHP?

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).
There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).
The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment.
Further reading is available on these things in the PHP documentation.
NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?> instead of <?=$var?> depending on your PHP setup.
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the <% and %> markers just right.
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</html>\n";
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
This is how I do it:
<?php if($contition == true){ ?>
<input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
<p>No input here </p>
<?php } ?>
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>

Categories