Can I configure PHP to automatically format the HTML it generates? - php

For example…
This PHP code
<?php
echo '<html>';
echo '<body>';
echo '<h1>Header One</h1>';
echo '<p>Hello World!</p>';
echo '</body>';
echo '</html>';
?>
Generates this HTML markup
<html><body><h1>Header One</h1><p>Hello World!</p></body></html>
Are there any functions, libraries or configuration options to make PHP automatically apply some simple formatting (line breaks & indentation) based on the nesting of html tags generated in the output? So that instead something like this would be generated…
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>

You could try templating engines like Smarty, Savant, PHP Sugar or VLib.
Or you could go commando with output handling (which I think is a hack). ob_start('ob_tidyhandler');
For the output handling, Tidy might not be installed or enabled, typically the package you will need to install is named php-tidy and you will need to uncomment extension=tidy in your php.ini

You can put html in your PHP script without having to echo it. You also might want to look for a PHP template engine like smarty, so you can separate the view from logic.

I prefer to use heredoc strings and format/indent the HTML myself. Mixing HTML strings inside PHP code quickly leads to unreadable, unmaintainable code. Some advantages of this method:
Quotes don't need to be escaped.
You can put variables inside the heredoc strings.
Even when working with code that loops, you can output the HTML inside heredoc strings. If these strings are indented properly relative to your other blocks of HTML, you will still get HTML code that has good indentation.
It forces you to think about when you want to print HTML, and to print it in blocks instead of lots of little pieces sprinkled throughout your code (very hard to read and maintain).
It's better to separate the PHP code from the HTML as much as you can, whether this means using a templating engine or just putting all of the code before all of the HTML. However, there are still times when it's easiest to mix PHP and HTML.
Here's an example:
<?php
$text = 'Hello World!';
echo <<<HTML
<html>
<body>
<h1>Header One, with some '"quotes"'</h1>
<p>$text</p>
</body>
</html>
HTML;
?>

If I understand your question right, you want to pretty-print the HTML output.
This can be done by post-processing the output of your PHP script. Either by using PHP's output handling feature combined with the tidy extension­Docs:
ob_start('ob_tidyhandler');
Tidy is an extension specialized on cleaning up HTML code, changing indentation etc.. But it's not the only way.
Another alternative is to delegate the post-processing task to the webserver, e.g. output filters in Apache HTTP Server­Docs.

You could do this (my preference):
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
<?php echo '<p>Hello Hello!</p>'; ?>
</body>
</html>
Or:
<?php
$html = '<html><body><h1>Header One</h1><p>Hello World!</p></body></html>';
$tidy = new tidy();
$tidy->parseString($html, array('indent'=> true,'output-xhtml'=> true), 'utf8');
$tidy->cleanRepair();
echo $tidy;
?>";
...would print:
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>

...Or you can use the "<<<" operator where you can set formation by yourself:
<?php
echo <<<DATA
<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>
DATA;

If the below code looks useful to generate html with php, try this library
https://github.com/raftalks/Form
Html::make('div', function($html))
{
$html->table(function($table)
{
$table->thead(function($table)
{
$table->tr(function($tr)
{
$tr->th('item');
$tr->th('category');
});
});
$table->tr(function($tr)
{
$tr->td()->ng_bind('item.name','ng-bind');
$tr->td()->ng_bind('item.category','ng-bind');
$tr->setNgRepeat('item in list','ng-repeat'); //using second parameter to force the attribute name.
});
$table->setClass('table');
});
$html->setClass('tableContainer');
});

Related

Which one is better or must be in PHP scripts that can be applied for real projects?

As I am learning PHP, I want to know if I ever wanted to put HTML tags in the middle of a PHP script, I want to know which one is better or must be, out of putting them in PHP echo or breaking the PHP script where the HTML has to be started and then continuing the PHP script using tags php starting and closing tags. Below are two examples where you can get a clear idea.
page name: home.php example: 1
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
a=0;
while (a<=10){
?>
<input type = "text" max-length="20">
<?php
}
?>
</body>
</html>
page name: home.php example: 2
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
a=0;
while (a<=10){
echo "<input type = 'text' max-length='20'>";
}
?>
</body>
</html>
For learning purposes I will suggest you use <?php ?> and <?= ?> to break out of HTML. Echo’ing HTML may confuse you while learning (as someone earlier pointed out code highlighting). In your journey through learning, consider learning about MVC and how you can apply in simple ways to fit your needs. It helps you separate presentation from logic.
This is really just a matter of preference, both are acceptable. Typically if you have quite a bit of HTML DOM to insert, you'd break php with ?> and then reopen when necessary. If you have just a single line of HTML that needs to be inserted, a simple echo works perfectly.

Do I need to echo html inside included php file

I just learned how to include php .Here's the index or main php file
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php include 'header.php'; ?>
</body>
</html>
now in header.php file which way is better to print html
Way 1 directly use html without php
<header>
<h1>Header</h1>
</header>
Way 2 Using php and echo
<?php
echo '
<header>
<h1>Header</h1>
</header>
'
?>
Another quick question. Will it work if I use .html for the base or index file ??
sorry for my bad english
Directly use HTML without PHP:
<header>
<h1>Header</h1>
</header>
As for your second question:
The file you're using include() in must have .php extension, but the file that's being included doesn't necessarily need the .php extension. The .html extension would work fine as well.
Just include the PHP file.
BTW, in case you haven't, read about this too:
Difference between require, include and require_once?
HTH.
you should use include_once ;-)
http://us2.php.net/manual/en/function.include-once.php
There are a few ways to go around it. Rather than echoing everything, I like to go like this:
<title><?php echo $title; ?></title>
Or if I have a nice block to work with, maybe within an if statement, I also like to go like this :
<?php if($weather = "sunny") { ?>
<div id="sunny">
<p>It's a beautiful day outside.</p>
</div>
<?php } // end if($weather = "sunny")
else { ?>
<div id="sunny">
<p>Today is yucky.</p>
</div>
<?php } ?>
The answer is sometimes different. If you use the same header on a lot of pages, use Way1. If you're only doing this in one place, you want to use Way 2 (or keep it in html), since it's more readable at quick glance to someone studying the page.
You can use .html for the file if you change the server config to tell it to look at it for php first, but you shouldn't do that, it just increases complexity and may have unintended consequences if you do it wrong.
Use .php or .phtml for files with any amount php in it. The only distinction you can make is to use .phtml files for files that are mostly html.

Is there anyway to produce readable HTML source from PHP?

I'm not very experienced at php, so if there's an easy function for this, I'll feel like an idiot.
When coding in PHP, at the point where you need to echo some HTML code, I have found I have either one of two options.
A: echo "<!--html text here-->";
B: echo "\t\t\t<!--html text here-->\n";
If I were to use method A throughout the code, looking at the php code from client side using view-source produces a solid block of code which is difficult to read.
If I were to use method B, it looks fine client-side, but the actual source code looks messy.
Is there anyway to keep both server and client-side appearance clean?
Something like this
<?php
//php code here
?>
//html code
<h3> <?= $justADynamicVariable ?> </h3>
<?php
//continue php code
?>
Un-readable front end code is caused by poor factoring of your PHP code
The wall-of-text issue occurs because your code is messy. You have logic and display code in the same place (evident from the fact that you're echoing HTML from a PHP block) and this will always produce unreadable and ugly code.
Look at Model-View-Controller pattern, and separate out your logic code from your display code. Then, write your display code in a primarily HTML format with some in-line PHP:
<div>
Welcome back <?= $this->username; ?>
</div>
If you're having to echo HTML code from a PHP block, your code is probably factored wrong.
Other useful tricks to produce readable code:
Use alternative PHP control blocks
This:
<div id='somediv'>
<?php if($something): ?>
Some stuff
<?php endif; ?>
</div>
is infinitely more readable than this:
<div id='somediv'>
<?php if($something) { ?>
Some stuff
<?php } ?>
</div>
And it's definitely better than this which is probably what you're using now:
<?php
echo "<div id='somediv'>";
if($something) {
echo "Some stuff";
}
echo "</div>";
?>
You can just close the php tag (?>), write the html block and return to php (
Use a templating engine, like Twig http://twig.sensiolabs.org/ it allows you to separate your logic out of your templates so you can write really easy to markup with simple syntax to drop in dynamic variables.
or
Use a browser like Chrome, which will auto indent your source for you when you use the Web Developer Tools http://discover-devtools.codeschool.com/. You can even copy paste the results really quickly to a new file. In general, it's a bad idea to fret over outputting well spaced html since software can clean it up so easily.
There are lot's of ways to produce html, depending or it's a single line or an entire block of HTML.
The important thing is readability.
echo "<div><p>Hi ".$name."</p></div>";
Isn't unreadable persé, it might be annoying because it won't get highlighted in many IDE's.
This is a good reason to always seperate html and php, meaning always put html parts outside of your php tags.
So you could end your php block before and open it again after :
if(TRUE) {
?>
<div><p>Hi <?php echo $name;?></p></div>
<?php
}
If you have PHP within a large file mostly containing html you are better of using php control blocks:
<!--html text here-->
<?php if(TRUE):?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
</php endif;?>
<!--html text here-->
You could also use heredoc
echo <<<EOD
<div>
<p>This is html</p>
</div>
EOD;
Or output buffering:
ob_start();
?>
<div>
<p>Hello <?php echo $name;?></p>
</div>
<?php
$html = ob_get_clean();
echo $html;

PHP or HTML first or does it matter?

I have a possible stupid question, but I'll ask it anyway.
Does it matter what goes first, PHP or HTML code?
For example: Does PHP go before HTML, after HTML or does it matter at all?
<?php
echo "This is text";
?>
<html>
<head>
</head>
<body>
<center>
<font size="2">This is text</font>
</center>
</body>
</html>
Or:
<html>
<head>
</head>
<body>
<center>
<font size="2">This is text</font>
</center>
</body>
</html>
<?php
echo "This is text";
?>
Or:
<html>
<head>
</head>
<body>
<?php
echo "This is text";
?>
</body>
</html>
The third one is the correct way (assuming you want the text to echo out in the body).
PHP can jump in and out of HTML as you have shown above.
<html>
<head>
</head>
<body>
<center>
<font size="2"><?php echo "This is text"; ?></font>
</center>
</body>
</html>
Personally I put the PHP as much as possible at the top of the page or even better outside the html page completely by using the html pages as purely views in the MVC pattern.
HTML doesn't go anywhere, but PHP script goes to server executes and response is returned to client side. Now that response is displayed/handled along with HTML code. HTML is only for browser where PHP script is used invoke service or do operations on database.
So, first PHP(Server) and then HTML(Client).
Add your php code before the html code.
This allows you to change the out type, set requied variables, add http response headers if you require, etc.
You can have a lot of php embeded tags in between the html.
The html in your question would be invalid, if you echoed output before or after .
Make sure your out is valid html.
Don't be bad to the browser just cause they will try to work with whatever you give them.
Onlything you have to maintain valid html structure. so you canot put anything outside the html tag. so third option is the most valid thing. but if you use any of others, it will print anything you want.
Not being a php person, will try to ans this in general sense. HTML is for browsers and php is serverside. When your pages reaches to the browser, there is only HTML, while, if I am not wrong as php should behave similarly yo jsp, at serverside html is seen as simple strings that need to be printed out at stream. So ideally, this should not matter what come first.
From good practice perspective, as this is php code(in my case jsp) whose output will be html, I try to give more feel of java to my code file.

HTML into PHP Variable (HTML outside PHP code)

I am new to php and wondering if I can have something like this:
<?php
...
magicFunctionStart();
?>
<html>
<head>...</head>
<body>...</body>
</html>
<?php
$variable = magicFunctionEnd();
...
?>
What I have to use right now is
<?php
...
$variable = "<html><head>...</head><body>...</body></html>"
?>
Which is annoying and not readable.
Have you tried "output buffering"?
<?php
...
ob_start();
?>
<html>
<head>...</head>
<body>...<?php echo $another_variable ?></body>
</html>
<?php
$variable = ob_get_clean();
...
?>
I think you want heredoc syntax.
For example:
$var = <<<HTML
<html>
<head>
random crap here
</html>
HTML;
I'm not really sure about what you are trying to accomplish, but I think something like the heredoc syntax might be useful for you:
<?
$variable = <<< MYSTRING
<html>
<head>...</head>
<body>...</body>
</html>
MYSTRING;
However if you are trying to make HTML templates I would highly recommend you to get a real templating engine, like Smarty, Dwoo or Savant.
Ok what you want to do is possible in a fashion.
You cannot simply assign a block of HTML to a php variable or do so with a function. However there is a number of ways to get the result you wish.
Investigate the use of a templating engine (I suggest you do this as it is worth while anyway). I use smarty, but there are many others
The second is to use an output buffer.
One of the problems you have is that any HTML you have in your page is immediately sent to the client which means it cant be used as a variable in php. However if you use the functions
ob_start and ob_end_fush you can achive what you want.
eg
<?php
somesetupcode();
ob_start(); ?>
<html>
<body>
html text
</body>
</html>
<?php
//This will assign everything that has been output since call to ob_start to your variable.
$myHTML = ob_get_contents() ;
ob_end_flush();
?>
Hope this helps you can read up on output buffers in php docs.
I always recommend to AVOID buffer functions (like ob_start ,or etc) whenever you have an alternative (because sometimes they might conflict with parts in same system).
I use:
function Show_My_Html()
{ ?>
<html>
<head></head>
<body>
...
</body>
</html>
<?php
}
...
//then you can output anywhere
Show_My_Html();
$html_content = '
<p class="yourcssclass">Your HTML Code inside apostraphes</p>
';
echo $html_content;
Its REALLY CRAZY but be aware that if you do it :
<?php echo ""; ?>
You will get it:
<html><head></head><body></body></html>
Keep calm, its only php trying turn you crazy.

Categories