I am new to PHP and I'm currently working through 'PHP for absolute beginners' book. In the book it is currently teaching about templating and using the StdClass() Object to avoid naming conflicts.
I have a file for templating called page.php and a file for my homepage called index.php.
My page.php code
<?php
return "<!DOCTYPE html>
<html>
<head>
<title>$pageData->title</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body>
$pageData->$content
</body>
</html>";
My index.php
<?php
//this correctly outputs any errors
error_reporting( E_ALL );
ini_set("display_errors", 1);
$pageData = new stdClass();
$pageData->title = "Test title";
$pageData->content = "<h1>Hello World</h1>";
$page = include_once "templates/page.php";
echo $page;
The errors i am receiving are
Warning: Undefined variable $title in C:\xampp\htdocs\ch2\templates\page.php on line 5
Warning: Undefined variable $content in C:\xampp\htdocs\ch2\templates\page.php on line 9
I don't understand this as it is exactly what the book is teaching any help would be appreciated and please if there are any better ways to use templating please remember I am a beginner so keep it simple!
Your page.php looks a little odd. return is not something I would use in context of printing html. Also, you are using php and html within the php tag which can't work. Try this:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageData->title; ?></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body>
<?php echo $pageData->content; ?>
</body>
</html>
You don't need echo $page in your index.php, let the page.php do that.
/Edit: There is also a typo in line 9: $pageData->$content; I corrected that.
I have a webpage called search.php
I want it to have a title/tab tag that looks like this:
<head>
<title><?php echo $number_count; ?> items found - Mysearch </title>
<head>
But the variable $number_count is 0 until later php scripts are called to query the database and display the items one at a time. At the end of the HTML I can easily display <p> <?php echo $number_count; echo "items found" ?> </p> and it works with the correct count.
It must be defined first.
Best (and only in this case) approach to do it is to do calculations first, then generate website output.
EDIT:
You can do it like that:
<?php
$count = 125;
?><!DOCTYPE html>
....
<title>Title count: <?php echo $count ?></title>
....
Is there a tool that will show me what my .php file looks like AFTER the "preprocessor" goes through it and includes all the "include" and "require" files? In other words, if I have a file called "index.php":
<?php
#My root index page
include 'vars.php';
include 'header.php';
include 'body.php';
?>
If the files are:
vars.php:
<?php
SITENAME = "MySite";
$where = "here";
include 'ThatOne.php';
?>
header.php:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>My page</title>
</head>
body.php:
<?php
print "<body>\n";
print "<H1>Hello World</H1>\n";
print "</body>\n";
?>
ThatOne.php
<?php
$ThatOne = "This One";
?>
I would like to be able to see that this page results in a working page that looks like:
<?php
#My root index page
SITENAME = "MySite";
$where = "here";
$ThatOne = "This One";
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>My page</title>
</head>
<?php
print "<body>\n";
print "<H1>Hello World</H1>\n";
print "</body>\n";
?>
This is obviously a contrived example, but I am working with a site with includes that are nested about 4 deep, and I would like to make sure that what PHP is working with is really what I want it to be working with.
I am fairly new to PHP, but I asked this question of a colleague who is also working with PHP and his reaction was "That would be really usedful, but I have never seen anything that will show that."
If you wish, you may create your own tool. Just use get_included_files and file_get_contents, as follows:
<?php
#My root index page
include 'vars.php';
include 'header.php';
include 'body.php';
$included_files = get_included_files();
foreach ($included_files as $filename) {
echo file_get_contents( $filename );
}
?>
According to the manual, get_included_files() will get any required or required_once files, too (see here). The only limitation is that you'll only be able to see text or HTML output, so vars.php wouldn't have visible content. If you change a pure php file by giving it an extension of .phps, then you can see the PHP source code which can appear highlighted.
I am using (or at least tying to) PHP HEREDOC function as a templating engine. I have implemented external caller string that can directly process external functions in HEREDOC, and that works successfully.
The problem I am facing now is that the order of certain functions appear to take precedence and execute first, regardless of other functions and/or code inside the specific HEREDOC.
How to fix that?
(Please note I am a PHP beginner. I have done my homework, but couldn't find a solution. Thanks.)
FUNCTION PROCESOR:
function heredoc($input)
{
return $input;
}
$heredoc = "heredoc";
HEREDOC TEMPLATE:
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
The issue at hand is with "{$heredoc(display_all_articles_in_a_html_table())}" call, which outputs before everything else, resulting in a broken HTML.
Any help appreciated, I am banging my head with this for quite a while now.
UPDATE:
using stuff posted in comments i tried to do something else, but this is ugly as hell, and I would have issues editing this at later date.
function testout()
{
$title = "This is document title";
echo "<!DOCTYPE html>";
echo '<html lang="en">';
echo "<head>";
echo '<meta charset="utf-8">';
echo "<title>". $title . "</title>";
echo "</head>";
echo "<body>";
echo splicemaster_return_message();
echo splice_quick_add_article_form();
echo display_all_articles_in_a_html_table();
echo "</body>";
echo "</html>";
}
(How it looks like is not important - I have a HTML processor function.)
UPDATE 2
OK, so I found "dirty" fix, tho that doesn't explain why the engine works as it does. (I also tested on another machine, with diff. php):
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
HEREDOC;
echo <<<HEREDOC
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
You shouldn't be using heredoc here. Or really be trying to render an entire html document within a function. This is how html should be rendered with php.
Note: I'm also pretty sure you can't call functions in a heredoc statement.
<?php $title = "This is document title"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo splice_html_title($title); ?>
</head>
<body>
<?php
echo splicemaster_return_message()
. splice_quick_add_article_form()
. display_all_articles_in_a_html_table();
?>
</body>
</html>
You can see how much cleaner this is, which makes it much easier to edit, when needed. You just put this in a file 'page.php' for example.
include_once('page.php');
And include it where ever you would call that function splicemaster_return_full_page.
I asked this (similar) question on other site while seeking why this happens, and found the culprit.
The problem was in called functions that echo (or print) output, instead returning it. When I switched to return, the code outputs appropriately.
This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
Given the HTML generated by my application.
function pagination(){
echo "<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t<li>...</li>\n";
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
If I add another container DIV, this doesn't produce correctly indented code.
Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?
Amazing question.
9 answers and 3 comments so far, and looks like nobody bothered to read the question body, but just repeated some gospel triggered by a keyword in the title - a most preferred manner to answer questions on the blessed site of stackoverflow.
Yet the question not that simple/one-layered.
I have to admit, it's ambiguous itself. So, we have to dig it out.
1) How do you indent your HTML?
Use templates, dude. Use templates. The only answer.
2) Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?
Of course there isn't.
PHP knows nothing of HTML, indents and such.
Especially when no HTML is ready yet(!)
3) If I add another container DIV, this doesn't produce correctly indented code.
The key question of the question.
The question for sake of which the question were asked.
Yet hardest of them all.
And the answer is kind of ones I showed total disagreement with, hehe:
Although relative order of tags is important, for the resulting large HTML it is possible to move some blocks out of row:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<!-- news list -->
<div>
<ul>
<li>1..</li>
<li>2..</li>
<li>3..</li>
<li>4..</li>
</ul>
</div>
<!-- /news list -->
</div>
<div>
<!-- pagination -->
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
<!-- /pagination -->
</div>
</body>
</html>
It will let you have proper indention in the meaningful blocks, yet keep the main HTML in order.
As a side effect it will keep your lines on the screen :)
To keep good indentation inside sub-templates, I'd strongly suggest using PHP-based templates. Not ugly HEREDOC for goodness' sake!
Here is only one rule to follow with PHP templates:
always keep PHP blocks to the left side. That's all.
To keep indentation between PHP nested blocks, just indent them inside <? ?>
Example:
<ul>
<? foreach ($thelist as $color): ?>
<li>
<? if ($color == $current): ?>
<b><?=$color?></b>
<? else ?>
<?=$color?>
<? endif ?>
</li>
<? endforeach ?>
</ul>
This will produce correctly indented HTML, while keeping order of both HTML and PHP in the template, making developer's life easer both at development and debugging.
Do not listen to anyone who says "no need to indent your code at all!". They are merely hobbyists, not the real developers. Anyone who have an idea of what debugging is, who had hard times debugging their code, would tell you that proper indentation is essential.
The answer could sound weird, but you should not worry about the generated code's indentation. Indentation is for readability, and should be only of concern on the programmer's side, not on the generated part (which is for browsers).
I agree with all comments saying don't bother but if you do have a case where doing so makes sense then you can pipe your HTML through HTML Tidy (or in your case PHP Tidy) using the indent option.
Most editors have some sort of formatting function which can be used to fix indentation. In Visual Studio for example you can hit Ctrl + K + D to nicely format your html.
I usually do it something like this if it's a more complicated html structure. This makes it easier to follow if you ask me, and you also can write your html normally instead of worrying about escaping quotes and things like that.
Since you're not in a PHP block when it's processing the HTML, it will come out as indented as you make it.
<?php
function pagination(){
echo "</ul>\n";
for($i = 1; $i <= 10; $i++)
{
?>
<li>...</li>
<?php
}
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
You could use heredoc syntax
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
Notice all of the indenting is preserved.
EOT;
?>
If you add \t in front of ul you should be able to see the code prettied up
<?php
function pagination(){
echo "\t<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t\t<li>...</li>\n";
echo "\t</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
I am a stickler for well formed code as well. Alot of people here said "firebug will indent your code for you". Well, what about when the markup delivered to the browser is modified through or injected into the DOM via javascript? Then firebug shows you the current state, not what you loaded from the server.
I also like my html to be visible and readable throughout my script. I generally do something like this, keeping track of PHP and HTML indentation separately (it is not to be able to put your cursor on an opening tag or { and just scroll the page down until you find the closing tag or } conveniently lined up with your cursors position.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div><?php
$thelist = array('Red', 'Green', 'Blue', 'Black');
echo '
<ul>';
foreach ($thelist as $color) {
echo '
<li>' . $color . '</li>';
}
echo '
</ul>';
?>
</div>
</body>
</html>
This outputs just like so,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
</div>
</body>
</html>
Notice is looks just like it should, and like it does in the script (this makes debugging simple for me). I use single quotes with HTML so I do not have to escape a trillion quotes (this makes concatenating strings a bit more manual but it is less work than all those back slashes; which also hinder readability within the script).
Once again, this is just how I do things and may not be the ideal way to handle formatting HTML. I just like to have my HTML nice and neat even when its mixed with PHP
The answer is, use templates.
If you properly separate your logic from your presentation, this question goes away. Your templates will have all the indenting or lack of indenting you want or need.
EDIT
Nonetheless, you can modify your code pretty simply:
<?php
function pagination($depth=0) {
$indent = str_pad("", $depth, "\t");
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination(1); ?>
</div>
<div>
<div>
<?php pagination(2); ?>
</div>
</div>
Alternatively, you can just pass in the indent you want:
<?php
function pagination($indent="") {
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination("\t"); ?>
</div>
<div>
<div>
<?php pagination("\t\t"); ?>
</div>
</div>
Edit: broke the code down into pages.
This code really only works with a template system.
Which can just be a basic:
// file: index.tpl.html
<html>
<head>
</head>
<body>
<div>Some header code</div>
<div>
{mainContent}
</div>
<div>Some footer code</div>
</body>
</html>
// file: functions.php
<?php
function pagination()
{
$output = "<ul>\n";
for($i = 1; $i <= 10; $i++)
$output = "\t<li>...</li>\n";
$output = "</ul>\n";
return $output;
}
function indent_html($html, $tag, $new_html)
{
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{'.$tag.'}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// Uses the indent from the line above to indent your new html
return str_replace("\n", "\n".str_repeat(" ", $spacePos), $new_html);
}
?>
// file: index.php
<?php
$html = file_get_contents("index.tpl.html");
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{mainContent}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// your pagination() needs to return html not output it
$mainContent = pagination();
$mainContent = indent_html($html, $tag, $mainContent);
// Uses the indent from the line above to indent your new html
$mainContent = str_replace("\n", "\n".str_repeat(" ", $spacePos), $mainContent);
// finally insert your html
$html = str_replace("{mainContent}", $mainContent, $html);
?>
Might need some modification if you want to use tabs instead of spaces.
I use spaces as it's more cross browser/application.