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.
Related
When writing PHP code in the past, I have often been plagued by the awkwardness of having to nest my HTML code in calls to print, echo or similar. This is alleviated to some degree by the ability to make parts of the code be literally outputted by closing the PHP tag and reopening it again after the output, eg:
<?php /*DoSomeStuff*/ ?>
Some HTML code.
<?php /*SomeMorePHP*/ ?>
However, I have never been clear on how this interracts with functions. For example, it is unclear to me if writing:
<?php
function myFunction() {
?>
Some HTML
<?php
}
?>
Will produce a function which upon being called will output that HTML, if the function will be parsed as empty but output that HTML during parsing, or neither, both or if this construct is just illegal entirely?
I am reluctant to base all my results on just trying this on some particular instance of PHP as I do not wish to beleive it works while in reality it might be undefined behaviour or think it doesnt work while I might just have an old or buggy PHP and I have never seen this construct used in any code.
Ideally I am looking for some kind of reference to documentation or specification which would clear this up.
I know this is not exactly answering your questions with a lot of references, but: This is valid (PHP Docs), although it doesn't look very nice, it's a common practice in some old but BIG frameworks.
You can try this and see what happens:
function htmlOut() {
?>
Some HTML output
<?php
}
htmlOut();
By the way I found an example, the default skin of MediaWiki (I would say they know what they are doing) is using just the method you have described.
/**
* Outputs the entire contents of the (X)HTML page
*/
public function execute() {
/**
* some code
*/
// Output HTML Page
$this->html( 'headelement' );
?>
<div id="mw-page-base" class="noprint"></div>
<div id="mw-head-base" class="noprint"></div>
<div id="content" class="mw-body" role="main">
<a id="top"></a>
<?php
/**
* some more code
*/
}
See the full code here: MediaWiki GitHub
Basically it will work as you expect it to be, which means that this HTML will be printed only on function invoke.
There's probably no documentation for your use case, but it's similar to condition expressions.
You could ask if similar question for code below:
<?php if ($expression == true): ?>
HTML1
<?php else: ?>
HTML2
<?php endif; ?>
Will PHP print both HTML parts, or only one depending on the condition?
Well, the doc says clearly that it works as it is expected to be.
I think we can say it's the same for functions/methods, because it's just "a block of code". It works with the same rule in many other cases like loops or swich
Reference: http://php.net/manual/en/language.basic-syntax.phpmode.php Example #1
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;
?>
I've got two channels that are related. The website is multilingual and the {lang} global variable contains the language (en / nl / de / fr).
Using the {{lang}-something} approach works throughout the whole site, but not within the related entries tag.
The output of {{lang}-something} should be the content, but it literally is {en-something}. So the language is inserted but it's not being parsed after that.
When I simply use {en-something} in the template (without dynamically setting the language) I do get the content.
Template snippet:
{related_entries id="product_usp_1"}
<div class="ups_item">
<h3>{{lang}-usp-title}</h3>
<p>{{lang}-usp-content}</p>
</div>
{/related_entries}
Any suggestions? Thanks in advance!
Well, it looks like {lang} is parsed pretty late in the process -- see Low's excellent help on this. This suggests that you might have joy moving the inner part of your example to an embedded template (a hack I strongly dislike even though it's often deployed!). So your original bit becomes:
{related_entries id="product_usp_1"}
<div class="ups_item">
{embed:lang_template}
</div>
{/related_entries}
and the embedded template (lang_template above) becomes:
<h3>{{lang}-usp-title}</h3>
<p>{{lang}-usp-content}</p>
I'm not entirely sure why, but this works:
<h3> {<?php echo '{language}';?>-usp-title} </h3>
<p> {<?php echo '{language}';?>-usp-content} </p>
This code is insite the related_entries tag, not embedded.
PHP Parsing stage: input
I am building my website completely in PHP. I am trying to make it as much flexible as possible.
I have seen there are some softwares made in PHP that are able to get a HTML page, and before showing it, the PHP code recognizes the code inside brackets {PHP Code} as PHP code, runs it and only then shows the final page.
<h1>Hi My Name is {echo $name}</h1>
How can I achieve the same? I know there is Smarty Code. But I do not want to learn Smarty, I just want to know how to check a HTML page with PHP, find every bracket and threat that as PHP before showing the page..?
Can you point me somewhere?
Are you looking for PHP's basic syntax?
If you enable short_open_tags (it usually is enabled by default), this will work:
<h1>Hi My Name is <?=$name?></h1>
otherwise, this will always work:
<h1>Hi My Name is <?php echo $name; ?></h1>
PHP is already a templating language - there often is no need to add another layer of templating on top of it.
I want to keep the template files separated from the php engine
In fact, you don't
Your template files would behave as native PHP files in every way.
So, there is asolutely no [logical] reason to prefer such a strange solution over native PHP.
use the php tags for the echo statement.
<h1>Hi my name is <?php echo $name; ?></h1>
Well, just point apache to index.php which includes phtml templates into itself. Use <?php ?> instead of { }.
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.