Is there anyway to produce readable HTML source from PHP? - 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;

Related

Sharing a code fragment all over the website

So, if I have a website containing two or more webpages with some same code fragment (e.g. side menu or top bar), how can I store this fragment in one place for using by all the webpages on the website?
I tried to put that repeating code to separate php file, like:
<?php echo "<div id='menu'> ... </div>";
and then just use
<?php include "menu.php" ?>
but problems occur with double-quotes inside double-quotes (considering I have PHP and JS scripts inside that "central" one, it's even more trouble), interpretation and so on.
What should I use (preferable HTML and PHP tools) to achieve that "code sync"?
Why are you echoing HTML?
How can I put double-quotes inside double-quotes?
You can escape the double-quote by prepending a backslash:
echo "<div id=\"some-id\">";
But, you're dealing with the wrong problem!
You're going along the right lines with re-using code, but you don't need to echo HTML. Any HTML outside of PHP tags will parse as regular HTML anyway, so just do it like this:
<div id='menu'>
...
</div>
Then require_once('menu.php'); to import the file. This way, you won't have to mess around with escaping nested quotes.
What if I have dynamic content in my menu?
Good question, then use something like this:
<div id='menu'>
<?php foreach($menuitems as $menuitem): ?>
<div id='<?php echo $menuitem['id']; ?>'>
<?php echo $menuitem['text']; ?>
</div>
<?php endforeach; ?>
</div>
By keeping the PHP and the HTML in separate tags, you create code which is easy to parse, easy to read and easy to maintain.
Similarly, don't use inline JavaScript
Keep your js in separate files, and call it from within your HTML like this:
<script src="script.js"></script>
You know you can just include 'menu.html' or include 'menu.php' without echo just using html tags and adding any php functionality inline like you would normally.

Large block of HTML in a PHP block

I'm using PHP to make my page more dynamic through query passing however I have a big chunk of HTML code that needs to have dynamic content inside but I don't know how to go about doing that without printing every statement:
One part in HTML:
<div class="review">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/rotten.gif" alt="Rotten" />
<q>Expect no intelligence or subtlety here, but if you're willing to put up with the sheer ridiculousness of it all, you might enjoy wallowing in Bekmambetov's shameless exhibition of narrative lunacy and technical fireworks in this movie.</q>
</p>
</div>
<div class="personal">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/critic.gif" alt="Critic" />
Frank Swietek <br />
<span class="italic">One Guy's Opinion</span>
</p>
</div>
The above code is for a single review however there could be any number of reviews which I am already taking a count of but I am also changing the image, quotes and text for all the reviews.
Is there a way of including all the tags without printing them all?
The regular way is to "close the php tag" and then reopen it after the HTML:
// php code here
?><html code goes here><?php
// php code here
However, there are a couple other ways. One is to use include.
// php code here
include('template.file.php');
// php code here
and inside your html code, you use have something like this:
<htmltag><?= $php_value ?></htmltag>
You can even use include within a function.
Alternatively, you can use a template system like Handlebars, Mustache, or Twig. Or you can just continue to build large strings, which is what I do. I set up templates, merge them with data to produce strings, and then emit the strings. The main thing I gain from using the templating system is that I can save up the strings to emit them at the end, and thus, have the ability to alter the HTTP header before my output is sent. If I used include() or code blocks, the code is emitted immediately, and I cannot modify HTTP header values.
Additionally, by building up the strings, I can save them to files and use these precalculated chunks to improve the site's speed.
<?php
//PHP code section
$wolrd = 'world';
?>
We are back in HTML
Hello <?= $world /* and some PHP echoing with a 'short tag' on same line with HTML*/ ?>
Suggested reading:
http://www.smarty.net/ (I'm not a fan but you should be aware of it)
MVC - Model - View - Controller
You should only be using PHP to print your dynamic content
<img src="<?php echo $image_url; ?>" alt="<?php echo $image_alt; ?>" />
You can close PHP and start it again at any point
<?php
$string = "hi";
?>
<p>Lot's of HTML</p>
<?php
echo $string;
?>

Conditional embed HTML between PHP code blocks?

I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?
<?php if (something) { ?>
<p>Hello</p>
<?php } ?>
The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.
The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).
<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>
I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.
P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.
Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/
Here is what your doing:
<?php
//Anything inside me php processes
if($something)
{
echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>
Quick Note: It is good practice to separate your PHP from your HTML
<?php if ($something) { ?> <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
In your first example it is indeed true that <p>Hello</p> will be rendered if and only if 'something' returns true.
If you close a php tag with ?> but have an 'unclosed' execution, like if (blah) { ..., the PHP engine understands your desires and does accordingly.
Why?
The PHP engine is kept 'waiting' until the execution is closed with } and then the final result is evaluated and the browser continues on with the lines below.
Obviously if you leave out the final } you will see some errors, which tells you that PHP was expecting you to finish what you started and you did not
Both the php and html are parsed in-line. So, as it moves down your script it will run php scripts within tags, and display html in the order which they are placed. For example:
<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo
This will show as:
<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>
Basically just think of it as the server reading down your script and parsing whatever it sees as it goes. If there is html, it will display it and if there is php which does some sort of calculation and then spits out html, it will show the spat out html.
You can write php code anywhere in HTML using php code block
<?php echo "whatever " ?>
or
<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>
and if you use control structure ( if, switch etc.. ) then it will behave like all other languages, means if something is true then it will execute the part written between { }.
so if you write an undefined variable in if condition then it will not execute code block of because undefined variable is treated as false condition .
additionaly you can check any variable value by var_dump($variable)
PHP's Alternative syntax for control structures
<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
<p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
<p>The other thing is true! meh</p>
<?php else : ?>
<p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...

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

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');
});

incorprating css and html elements into php

I have a bunch of php files that I want to incorporate html (divs) and css (external stylesheets) elements into.
If any one has any tips / ideas on how to go about doing this I'd love to hear them :)
You could either :
Integrate HTML code in your PHP file,
Or have your PHP script echo the HTML content.
With the first solution, your PHP file could look like this :
<?php
$var = 10;
// some PHP code
?>
<div>
this is some HTML
</div>
<?php
// and some PHP code again
?>
For more informations about this, see the following section of the manual : Escaping from HTML.
While, with the second solution, your PHP file could look like this :
<?php
$var = 10;
// some PHP code
echo '<div>this is some HTML</div>';
// and some PHP code again
?>
Basically, you are free to mix HTML and PHP code in the same PHP script : outside of <?php ... ?> tags, things will not get interpreted as PHP code.
All you need to do is exit php and write html as normal:
<?php
// php code
?>
<div>
<p>Some html</p>
</div>
<?php
// more php code
?>
Take a look at the PHP alternative syntax for control structures. It is often times more comprehensive when you start mixing with plain HTML:
<?php if(...): ?>
<p>paragraph</p>
<?php endif; ?>
Instead of:
<?php if(...) { ?>
<p>paragraph</p>
<?php } ?>

Categories