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;
?>
Related
I have a question, there is a way to update $error when his value change on external listPagPrinc.php?
<div id="statoPag">
<h3> Stato : <?php echo $error; ?> </h3>
</div>
<div class="headerCont">
<?php
include('procedure/listPagPrinc.php');
?>
</div>
Not as-is, no. Think of these HTML/PHP files like an office printer, once it prints out each line, you can't "go back" and print over it
In this example, all of the first 5 lines are run and effectively "set in stone" before anything is called in procedure/listPagPrinc.php.
If, and this is just speculation, you can't simply include procedure/listPagPrinc.php before you render $error because it also is printing additional HTML, you just need to encapsulate its code in functions as best as possible: One to set the value of $error, and a separate one to output the HTML you need.
You need to update the text content of the tag; you can do this with e.g. jQuery at runtime. This is the preferred way if some tags, and only those, change during the lifetime of the application page, and you do not wish to reload the whole page from scratch.
In this case, from listPagPrinc.php, you can output some Javascript code:
echo <<<JAVA1
<script>
alert("Ciao, mondo");
</script>
JAVA2;
or in your case using jQuery
echo <<<JAVA2
<script>
$('#statoPag h3').text("Errore!");
</script>
JAVA2;
Very likely the call will need to be inside a jQuery onDocumentReady function to be sure that it executes.
A better and faster way (and as #arkascha observed, nicer and more robust): you can generate the header from listpagPrinc.php or from a wrapper.
// file listPagPrincWrapper.php, replace your current file
// Ideally listPagPrinc could return a text value. In case it is
// printing it, as seems likely, we capture the output. This way
// we don't neet to modify the existing code.
ob_start();
include('procedure/listPagPrinc.php');
$lpp = ob_get_clean();
// At the end, we do the output part.
print <<<HTML
<div id="statoPag">
<h3> Stato : {$error}</h3>
</div>
<div class="headerCont">{$lpp}</div>
HTML;
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.
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;
I got the code below from a tutorial that teaches how to make wordpress plugins. It has some unusual PHP tags. For example,
a) 3rd line from the bottom, there is an opening <?php tag.
b) And, also, after $base_map_url is set, there is a closing ?> tag.
This is very different from what I've learned, yet the code works.
c) Also, in all the plugins the author has built, there is an opening <?php tag at the very top but not a final closing one.
What is happening here, can you explain?
<?php
/*
Plugin Name: Map plugin using shortcode
Plugin URI: http://example
Description: This plugin will get a map of whatever parameter is passed
Author: Drew
Version: 1.0
Author URI: http://www.blah
*/
function smp_map_it($addr)
{
$addr = "1600 Pennsylvania Ave. Washington, D.C.";
$base_map_url = 'http://maps.google.com/maps/api/staticmap?sensor=false&size=256x256&format=png¢er=';
?>
<h2>Your map:</h2>
<img width="256" height="256"
src="<?php echo $base_map_url . urlencode($addr); ?>" />
<?php
}
add_shortcode('map-it','smp_map_it');
It is just leaving a PHP block for HTML output.
Functions shouldn't really do that. That is why WordPress gets so much crap, e.g. the_content() that just dumps content (as if people are too incompetent to use echo).
The best way to do it is simply have a view file which handles your HTML and some basic PHP constructs and control structures such as echo, foreach, if, etc.
The trailing ?> in a file is unnecessary, and Zend coding standards ask you to never place it. It can often be the cause of Headers already sent when some pesky whitespace ends up after it.
When you close the PHP tag, it just becmes equal to:
echo ('<h2>Your map:</h2>
<img width="256" height="256"
src="');
There are two approaces to coding PHP. One inserts PHP into HTML, this is used by frontend developers. Template languages use this style in general:
<img src="<?php echo ($url); ?>">
The other style is more like programming then template writing:
<?php
echo (printf ('<img src="%s">', $url));
<?php marks the beginning of php code for the php parser
?> marks the end of php code for the php parser
/* marks the start of a comment which will be ignored by the parser
*/ marks the end of a comment which will be ignored by the parser
This function is sending output directly rather than using echo statements where the content falls outside the php tags.
While this kind of approach is often discouraged (coming out of the PHP context while in a function body isn't considered good practice) there isn't anything about it that would make it not function.
It is however, very bad code. Outputting in function bodies very often leads to header errors and other comforts when trying to perform redirects or session management.
It is not strange, it is crap. He is embeding HTML in PHP (sin anyway), and he is doing it bad.
Last PHP tag can remain open.
I have blocks of HTML code in a MySQL database and my framework needs to print these within a PHP template which will be outputted to the browser. To do so I make this call:
</tr>
<!-- Section 3 -->
<?php echo SIN_SiteView::get('section3') ?>
<tr>
Which gets the code either from the APC or MySQL, now the code it obtains looks like this:
<td height="280" colspan="2" bgcolor="#00abd2">
<a href="#">
<img src="<?php echo SIN_Utilities::l("image", "home_flash.png")?>" width="710" height="280" border="0" />
</a>
As you can see I need to run all images through a method known as "l" which I use to easily change images paths. Now the issue is if I echo that block of code it will simply be echoed as a string and not work.
I tried surrounding the php with '. [code] .' and removing the php but that also did not work. Does anyone have any ideas on how I could properly echo this to the page.
Thanks.
UPDATE: I think I need to be using the eval() command thanks to some of the comments, I simply do not understand how to implement it in my situation. Any simple examples would be greatly appreciated, for example how do I change this line:
<?php echo SIN_SiteView::get('section3') ?>
To echo the entire block featured above, thanks again.
I think you want eval rather than echo. See this slightly different question.
My solution would be to eval '?>'.$myhtml.'<?php'.
Is the marketing team adding the php code to the html you are storing?
If not, maybe you could change your <?php echo FUNCTION() ?> into #FUNCTION() and evolve your SIN_SiteView::get() into your own templating interpreter?
I agree with cHao though; it would probably be easier to adopt one of the templating packages out there and convert your data over.
You'll need to use eval to evaluate the inline PHP. However, this is potentially quite risky (eval is evil, etc.), especially if any of the content that's being fetched is user sourced.
e.g.: At the very least, what's the stop the user inlining...
<?php die(); ?>
...within the content they enter.
As such, you'll need to take a great deal of care, if there's really no alternative to this approach.
Some updates:
If you're new to PHP I'd recommend having a re-think. Chances are there's no need to use eval. (Unless there's a dynamically customised content on a per-user basis then you don't need it.) What are you trying to achieve?
What specific error/problem are you having? (I presume you're using var_dump or print_r for debug purposes, etc.) As the content you need to eval isn't pure PHP (it's HTML with PHP in) you'll need to embed the PHP close and (re-)open tags as #Borealid illustrated.