How do I insert an HTML page using PHP? - php

I wanted to know, is there any way to insert an HTML page into PHP without using the include function? I do not want to use an external html file, I want to write the html coding directly into the php coding.
Thanks for your help!

Interleave it:
<?php
// Some php code.
?>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>Header</h1>
<?php /* More php code. */ ?>
<p>Blah!</a>
</body>
</html>
<?php /* Even more php. */ ?>
From a best practices point of view, though, avoid doing this - having business logic (PHP) and presentation (HTML) in the same place makes maintaining harder.
EDIT: To address your comment. You can either do it the same way, or use echo:
<?php if (x == 5) { ?>
<p>Blah!</a>
<?php } else {
echo '<p>Bleh</p>';
} ?>

If you need to include snippets of HTML based on conditions, you can interleave code like this. In this case it's convenient to use the alternative syntax for loop controls
<?php if ( $var ): ?>
<html>
<title>YAY</title>
</html>
<?php endif; ?>
so the code is clearer to read and you retain HTML syntax coloring (if your editor supports it).

It is very bad habit to mix HTML and PHP (for more than just output control), but here you go:
$html = "<div>This is HTML</div>"
echo $html;
or Heredoc syntax:
$html = <<<EOF
<div>
<p>
Some longer HTML
</p>
</div>
EOF;
echo $html;
or using alternative syntax for control statements if the output depends on some condition (or if you loop through an array etc.)(which is far better than building HTML with strings):
<?php if($foo): ?>
<div> Some HTML output </div>
<?php else: ?>
<div> Some other HTML </div>
<?php endif; ?>
or just
<?php //PHP here ?>
<div>HTML</div>
<?php //more PHP ?>
<div>more HTML</div>
<?php //even more PHP ?>

Related

How to set title with data from included PHP file

I have a website with a template page that is something like this
<html>
<head>
<title>{{TITLE}}</title>
</head>
<body>
<div id = "header"> ... </div>
<?php include 'content.php'; ?>
<div id = "footer"> ... </div>
</body>
</html>
And then content.php would look something like this
<?php
$title = "xx";
#other php code here
?>
<p> more content </p>
My question is whether there is some way to set this up so that I am able to set the title from the file included in the middle of the page (without using javascript). I know that most people suggest including it at the top but if I were to do that the html would be at the top instead of between the header and the footer. I've wracked my brains for a while and I haven't really figured out a good way to do this (and there are a variety of possible files to be included; content.php is just an example, so I really do need some way to do this dynamically). I want to avoid putting too much code outside of the template. Any ideas?
Use output buffering:
<?php
ob_start();
include 'content.php';
$content = ob_get_clean();
?>
<html>
<head>
<title><?=htmlspecialchars($title)?></title>
</head>
<body>
<div id = "header"> ... </div>
<?=$content?>
<div id = "footer"> ... </div>
</body>
</html>
I'm not sure if you're using a templating engine or not (something like Laravel's Blade templates allow for this, I believe), but assuming you are using straight PHP, I have found the most efficient way to do this is to approach from the opposite direction and include the template file in each of my content files.
For example, I may have template.php, which has multiple functions, like this:
<?php
function createHeader($title, $keywords) {
//echo or <<<EOD your header with the set variables
}
function createFooter(...) { ... } //etc
And then, in my 'child' files, I would do:
<?php include('template.php'); ?>
<?php createHeader("My Website Front Page!", "fun, good times, joy"); ?>
<h1>My page content</h1>
<p>Content goes here</p>
<?php createFooter(...); ?>
This is a different structure from what you were attempting, though, and may not retain your intended structure.

CakePHP Recommended syntax for templates (views)

Ever since i've used CakePHP, I asked myself about the deeper sense of the recommended syntax of CTP-files, which is basically a HTML-file with all PHP code bracketed with tags. I find this very hard to read and I should think that the context switches between HTML and PHP would add some performance penalty.
Wouldn't it be faster and clearer to collect all output in a string and echo it at the end?
But there is some deeper sense for sure, just that i don't see it..
To make myself clearer, here's an example:
CakePHP:
<?php if (!empty($file['User']['email'])): ?>
<div class="mailto"><?php echo $this->Html->link($file['User']); ?></div>
<?php endif; ?>
<?php if (!empty($file['Document']['comments'])): ?>
<div class="file-comment file-extra column grid_6">
<div class="content"><?php echo $file['Document']['comments']?></div>
</div>
<?php endif; ?>
My approach:
<?php
$out = '';
if (!empty($file['User']['email'])) {
$out .= '<div class="mailto">'.$this->Html->link($file['User']).'</div>';
}
if (!empty($file['Document']['comments'])) {
$out .= '<div class="file-comment file-extra column grid_6">'
.'<div class="content">'.$file['Document']['comments'].'</div>'
.'</div>';
}
echo $out;
?>
So my question is: What are the drawbacks to my approach compared to CakePHP's ?
First things first: writing your entire template as PHP, then echoing it is not a great idea. As a general rule of thumb, I avoid echoing HTML from PHP ever, if I can. there are many reasons, but the main one will be the lack of syntax highlighting in your IDE.
Anyway, code formatting is entirely down to personal preference, but if you're writing your templates like this:
<?php if (!empty($file['User']['email'])): ?>
<div class="mailto"><?php echo $this->Html->link($file['User']); ?></div>
<?php endif; ?>
<?php if (!empty($file['Document']['comments'])): ?>
<div class="file-comment file-extra column grid_6">
<div class="content"><?php echo $file['Document']['comments']?></div>
</div>
<?php endif; ?>
...it's no wonder you can't read them.
There are a few things you could try, to make your code clearer and easier to read. Again, these are down to your own personal preferences, and you could get into the habit of using some or all of them.
Format your HTML properly, with indentations for child elements.
Add white space between lines of code that are too busy, particularly between lines of PHP and lines of HTML.
Use short echo tags syntax (<?= instead of <?php echo).
Assign the more complex PHP values to variables so that your HTML is easier to read.
Remember to comment your code (HTML or PHP), particularly adding HTML comments so that you can easily see separate components of your template at a glance.
Example
<?php
$user = $file['User'];
$comments = $file['Document']['comments'];
?>
<!-- User -->
<?php if (!empty($user['email'])) : ?>
<div class="mailto"><?= $this->Html->link($user); ?></div>
<?php endif; ?>
<!-- File Comments -->
<?php if (!empty($comments)) : ?>
<div class="file-comment file-extra column grid_6">
<div class="content"><?= $comments; ?></div>
</div>
<?php endif; ?>

What is this convention of using php code inside the first html tags?

I was referring the page.tpl.php(Drupal 7 theme) for understanding the code. I found the following code,
<?php if ($site_name || $site_slogan): ?>
<!-- !Site name and Slogan -->
<div<?php print $hgroup_attributes; ?>>
<?php if ($site_name): ?>
<h1<?php print $site_name_attributes; ?>><?php print $site_name; ?></h1>
<?php endif; ?>
<?php if ($site_slogan): ?>
<h2<?php print $site_slogan_attributes; ?>><?php print $site_slogan; ?></h2>
<?php endif; ?>
</div>
<?php endif; ?>
Can you see the code in third line, <div<?php print $hgroup_attributes; ?>> WHY the php code is inside the first div tag of html? Same thing in later part of code also, as you can see h1 and h2 code. So, what is this convention of combining the html and php in so complicated way? and how should I read that?
Combining HTML and PHP code in Drupal templates is actually a very strong feature. In this case, $hgroup_attributes will probably contain some classes that style the div. Printing it in the template results in something like
<div class="SOME_CLASSES"> ... </div>
If you're further interested in the variable $hgroup_attributes, you can inspect by pasting <?php dpm($hgroup_attributes); ?> in your template file after you've installed the Devel module.

Return big HTML block with some php without make string

How can i return big html block with some php by using <<<HTML HTML; .
return <<<HTML
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn(); ?>
<?php if($isflag){?>
<span>DO not do this</span>
<?php } ?>
<?php echo $whatever; ?>
HTML;
I can't understand what will work and what will not! how should i use this kind of return <<<HTML HTML; block with some php variable that i need to echo and some function that echo some thing (not return)
You can use 'capture output' for this task. see Output Control Functions
i has some example code that i have just tested. It captures the output of the div tag in $out1 and shows it again later.
This technique is used in many 'templating' libraries and in 'views' in the 'frameworks'.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test of Output control functions</title>
</head>
<body>
<?php ob_start(); // capture the buffer ?>
<div style="border: 4px solid red">
<p>This is a test paragraph</p>
<p>This is test PHP code: <?php echo time(); ?></p>
</div>
<?php $out1 = ob_get_contents(); // end capture ?>
</body>
</html>
<?php echo $out1; // output now or save for later. ?>
<?php var_dump($out1, strlen($out1)); ?>
<?php exit; ?>
Okay, google heredoc syntax for PHP.
but this is how it works (which I think you are trying to do.
$html = <<<HTML
<div>
<h1>$phpVariableTitle</h1>
<div>
{$thisFunctionEchosomthingNotReturn()}
</div>
</div>
HTML;
return $html;
Try that. IMPORTANT! heredoc syntax requires your closing tag be left aligned with no tabs. So make sure there are no spaces or tabs to the left of your heredoc tags, in this example my heredoc tags are called HTML. Also, wrapping your php variables/functions with curly braces is optional but good practice for this method. NO PHP tags in side heredoc block.
Hope that helps.
To make a conditional statement work inside you need to use a function:
class My_Class {
public function myCondition($param) {
if($param === true) {
return '<p>True</p>';
} else {
return '<p>False</p>';
}
}
}
$object =new My_Class();
$html = <<<HTML
<div>
<h1>Conditional Statement</h1>
<div> {$object->myCondition(true)} </div>
</div>
HTML;
something like that should work. But I haven't tested it.
I am unable to understand your question properly may be this may help:
<HTML>
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn();
if($isflag){?>
<span>DO not do this</span>
<?php }//Closing If if it ends here.
echo $whatever; ?>
</HTML>
You cannot write control structures / functions logic inside of HEREDOC syntax.
Alternate way..
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn(); ?>
<?php if($isflag){?>
<span>DO not do this</span>
<?php echo $whatever; }?>

How to output formatted HTML from PHP?

I like to format all my HTML with tabs for neatness and readability. Recently I started using PHP and now I have a lot of HTML output that comes from in between PHP tags. Those output lines all line up one the left side of the screen. I have to use /n to make a line go to the next. Is there anything like that for forcing tabs, or any way to have neat HTML output coming from PHP?
If there is relative bigger blocks of html you are outputting then HEREDOC syntax would help you format the html the way you want witout bothering much about echo tabs using php.
$html = <<<HTML
<html>
<head><title>...</title></head>
<body>
<div>$phpVariable</div>
</body>
</html>
HTML;
If you use some tool to parse your html , remember it will also add an extra overhead of processing and data payload for each request so you might want to do it only for debug purposes.
There's the tidy extension which helps you to (re-)format your html output.
But it has a little price tag attached to it. Parsing the output and building an html dom isn't exactly cost free.
edit: Could also be that you're simply looking for the \t "character". E.g.
<html>
<head><title>...</title></head>
<body>
<?php
for($i=0; $i<10; $i++) {
echo "\t\t<div>$i;</div>\n";
}
?>
</body>
</html>
or you nest and indent your php/html code in a way that the output is indented nicely. (Sorry for the ugly example:)
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++) { ?>
<div><?php echo $i; ?></div>
<?php } ?>
</body>
</html>
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++) { ?>
<div><?php echo $i; ?></div>
<?php } ?>
</body>
</html>
Actually this is a good example but in this case it's better to use Alternative way of doing things
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++): ?> // notice the colon
<div><?php echo $i; ?></div>
<?php endfor; ?>
</body>
</html>
Reference

Categories