PHP and HTML formatting, super basic question - php

I got to a phase in my code where I have too much code and too much HTML is depended on the consequences of some server conditions.
I simply want to know, is there any way to get around the:
<?php if (cond) echo '<p class="someclass">some HTML</p>'; ?>
?
I just wish there was something like in C where you can simply go like:
#ifdef x
do_a_lot_of_html_stuff;
#endif
All I can see that I can do now is go like:
<?php if (x) require_once("includes/all_needed_part.php"); ?>
Thanks !

Not exactly sure what you're asking, so if I am understanding your question correctly, you're looking for a way to print off blocks of HTML with PHP?
<?php if ($a == $b): ?>
<div>a == b</div>
<p>a is equal to b</p>
<?php else: ?>
<div>a != b</div>
<p>a is not equal to b</p>
<?php endif; ?>

I generally do it like this:
<?
function print_heading()
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><? print_title(); ?></title>
<link rel="stylesheet" type="text/css" href="..." />
<script language="javascript" type="text/javascript" src="..."></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="title" content="<? print_title(); ?>" />
</head>
<?
}
?>
But I would think that replacing function print_heading() with if (condition) would work too.

There's an alternative syntax:
<?php if($x): ?>
do_a_lot_of_html_stuff;
<?php endif; ?>

You can add HTML between PHP conditions as follows:
<?php
$a=1;
if($a==1){ ?>
<div>All the HTML Stuffs</div>
<?php } ?>

You may use the alternative syntax for control structures in combination with the heredoc-syntax.

You can do something like:
<?php if( cond ) { ?>
SECRET!
<?php } ?>

I would recommend that you check out a template engine, many exist for PHP with one of the most mature being Smarty. One of the newer (and cleaner) solutions is Twig, which is employed by the Symphony framework.

i guess you are at a point in your code where you should use Object Oriented Programming.
procedural coding is good but you'll eventually reach the point where there is just to much code in your page.

well you could use a c like syntax and still can do lots of stuff like.
This is typical php approach of using if using c like syntax.
<?php
if(1==1):
echo 'i can do lots of stuff here';
$variable = 'i hold some value';
$array = array('1','two','three');
endif;
?>
another way you could implement is by using brackets. for example.
<?php
if(condition) {
//do some stuff here
} else if(cond) {
//do another stuff here based on some conditions
} else if(cond) {
//you can extend the nested elseif as many times as you like
} else {
//else execute this.
}
?>

Guessing you are asking if there are frameworks available for php? The answer is yes, and here is at least one good one: http://cakephp.org/

Related

Querying database without using echo, producing results for design

there's something that's giving me a bit of a headache at the moment. I am querying a database retrieving some data after clicking a link from a previous page.
Easy enough I get to play about with some code in the 'echo'. Problem is in the ‘echo’ as I need to put in php includes and general html/design code for design purposes. Is there a way or a method where I can write the code but then call variables again later and have the ability to place other php code such as includes? Basically something which is going to let me have to have the code but then allow me to concentrate on the design aspect of my page.
Any help much appreciated.
<?php
if(!empty($_GET['book_url']))
{
$sql = "
SELECT articles.id, articles.order_ref, articles.art_title, articles.art_book, articles.art_url, book.id AS bookid, book.book_name AS book_name, book.book_url AS book_url
FROM articles
LEFT JOIN book ON articles.art_book = book.id
WHERE book_name = \"" .$_GET['book_url'] . "\"
ORDER BY id ASC
";
// then do the query, etc....
}
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
////////Show Stuff
";
?>
You can separate the code and the HTML by putting the code in <?php ?>. Then, in your HTML you can have short code snippets that print the work you did in the code sections. Like this (there might be a syntax error or two, I don't have Apache to test):
<?php
$name = $_GET['name'];
function stuff() {
// this would normally be long and complicated
return "stuff";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>title</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<!-- try to keep these short so you can focus on design-->
<h1>The name is: <?php echo $name; ?></h1>
<h1>The stuff is: <?php echo stuff(); ?></h1>
</body>
</html>
Alternatively, you can use a framework like Laravel which will provide a templating system.

Weird HEREDOC output order

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.

How can I access a variable in one block of PHP code in another block of PHP code in the same file?

I have something like this:
PHP code at the start:
<?php
$variable="example";
?>
Then HTML code:
<html>
<head>
<title>Title</title>
</head>
<body>
Then again PHP:
<?php
// code comes here, and I want to access variable $variable here.
?>
And then HTML code ends:
</body>
</html>
Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.
Not Required unless if you are accessing it under functions ( as it will lose their scope)
test1.php
<?php
$var = 1;
//.. your code...
?>
<html>.....
<?php
echo $var; // prints 1
whereas the below code won't work...
<?php
$var = 1;
function displayVar()
{
echo $var; // You will get a notice .. !
}
Just do what you stated above and it will work.
<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>
The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.
try this
echo ($variable);
or
print($variable);
If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.

How do you indent your HTML? [duplicate]

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.

Best practice: where to put the PHP code?

I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.
So I do:
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
...
</body>
</html>
This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
<div class="error_block">
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
</div>
...
</body>
</html>
Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.
I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.
Anyone can give their 2 cents on this issue? Thanks.
If you're looking for an alternate solution, I have one for you. What I like doing is having the logic in before the DOCTYPE
if(error) { $error = "Please do something" }
Than, down in the document I have a div just for the error (Thanks #Dave for the input)
<?php echo $error != '' ? '<div id="error">' . $error . '</div>' : ''; ?>
This div will not appear if there isn't an error (meaning $error is empty) and it makes it easier for you to style the error message the way you would like
#error { color:red; }
If you want to get fancy, you can use some jQuery to hide/show the div so that the error doesn't have to persist.
$('#error').show().delay(7000).fadeOut();
You should look into using try-catch blocks and generating exceptions if you want to do some post-processing with the error message, which includes display.
What is often forgotten is that PHP is an INLINE programming language in essence, this means it is designed to be processed by the server as the server reads down the page, and with this it is designed to be split up into chunks. Recently OOP (Object Oriented Programming) has been introduced to PHP making it more flexible.
So with this information in hand I would take the OOP path in this case and do something like:
<!DOCTYPE>
<?php
include("somefile.inc");
function bla()
{
...
}
function failureError($code){
if(!empty($code)) ...
}
if ($a = $b) {
code goes here
} else {
$code = 'error123';
}
?>
<html>
<head>
<script>
...
<?php failed($code); ?>
...
</script>
</head>
<body>
...
</body>
</html>
By writing using functions you can cut down your development time and group the majority of your code just calling what you need when you need it.
Another way of declaring your error class(es)/functions to help with server response time is to do something like:
if ($a = $b) {
code goes here
} else {
include("errorStuff.php");
}
This will only include the error class(es)/functions when an error is encountered.
Just remember when you're writing PHP with OOP techniques like this that the server will take longer to process the script than if you write inline. The biggest advantage to an OOP basis is it will cut down your development time and if done correctly it will make it easier to administer future updates to your script.

Categories