This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";
Related
How would one go about showing PHP code on user end. Sort of like w3School does?
Having lets say a grey area div, and then showing the code in there without activating it?
You can use html entities <?php in the html it will be rendered as <?php
You can use htmlspecialchars to encode your code to use html entities.
Use <pre> or <code> tags to wrap your code.
Take a look at http://php.net/manual/en/function.highlight-string.php to further see how you can make the code look pretty.
Since passing a large block of code to highlight_string() can be messy, you may want to look at output buffering in combination with highlight_string to output colorized php code.
Something like:
<?php
ob_start();
?>
phpinfo();
echo "this echo statement isn't executed";
<?php
$code = ob_get_clean();
highlight_string($code);
?>
Simply you can use following code to display php code on webpage.
highlight_string("<?php print('This is php code.'); ?>");
It will give output like
<?php print('This is php code.'); ?>
The first step is to not wrap that code in PHP tags. So instead of this:
<?
var sample = "code";
?>
You would have this:
var sample = "code";
It's not the code itself which triggers the server-side compile from the PHP engine, it's the tags which indicate to that engine what blocks of the file are code and what are not. Anything that's not code is essentially treated as a string and output to the page as-is for the browser to interpret.
Once you're outputting the code, it's then a matter of formatting it. The old standard is to wrap it in pre tags to get rid of HTML-ish formatting:
<pre>
var sample = "code";
</pre>
You can also apply CSS style to the pre tags (or any other tags you want to use for displaying code, such as div) as you see fit.
There are also very useful code syntax highlighting plugins and tools to make the code a lot "prettier". Google-code-prettify often comes highly recommended.
Typically this is done by showing code within <pre> or <code> tags.
You can use this template........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
It will show the source code and output following.
use the header function of php, this will rea
<?php
header("content-type: text/plain");
?>
The PHP code will just be a string that you can echo or print onto the page, no different than any other data you want PHP to display for you. If you want to keep the formatting (ex. the indentation), put it inside a <pre><code> block.
Ex:
$php_code = '<?php $foo = bar; ?>';
echo "<pre><code>$php_code</code></pre>";
Is it possible? If so, how?
If its not, do I have to abandon pug if I need to write PHP in my documents?
After searching around I didnt find anyone that has adressed this.
You can embed PHP in Pug templates the same way you would any literal plain text that you want passed through relatively unmolested[*]. There are a number of options covered in the docs, but I think these are most likely the best options for embedding PHP:
After an element, it will just work. For example, p Good morning, <?php echo $user->name ?>.
On a single line by itself. Since any line beginning with "<" is passed as plain text, any one line PHP statement (e.g., <?php echo $foo; ?>) will just work.
Multi-line PHP is the one case where it gets a bit complicated. If you're ok with wrapping it in an HTML element, you can use Pug's block text syntax: Put a dot after the element, then include your plain text indented underneath.
p.
<?php
if ($multiline) {
echo 'Foo!';
}
?>
If you need it outside an element, the other option is to prefix every line with a pipe:
|<?php
|if ($multiline) {
| echo 'Foo!';
|}
|?>
(Technically, the first line doesn't need to be prefixed due to point 2 above, but if using this method I would prefix it anyway just for consistency.)
To use PHP in attributes, you just need to prevent escaping by prefixing the equals sign with a bang: p(class!="<?php echo $foo ?>"). (Interestingly, support for unescaped attribute values was added specifically for this use case.)
Of course by default .pug files are compiled to .html files, so if you're using them to generate PHP, you'll want to change the extension. One easy way to do this is to process them using gulp with the gulp-pug and gulp-rename plugins, which would look something like this:
var gulp = require('gulp'),
pug = require('gulp-pug'),
rename = require('gulp-rename');
gulp.task('default', function () {
return gulp.src('./*.pug')
.pipe(pug())
.pipe(rename({
extname: '.php'
}))
.pipe(gulp.dest('.'));
});
I haven't worked extensively with Pug, so I don't know if there are any potential gotchas that would come up in real world use cases, but the simple examples above all work as expected.
[*] Pug still performs variable interpolation on plain text, but it uses the #{variable} format, which should not conflict with anything in PHP's standard syntax.
Since PHP doesn't care whether the "outside" code is HTML or really anything specific, you could simply use PHP as you normally would and have it output Pug-formatted code instead of HTML. For instance:
myPugTemplate.pug.php
html
head
title "<?= $this->title ?>"
body
<?php
// Since we're outputing Pug markup, we have to take care of
// preserving indentation.
$indent=str_repeat(' ', 2);
if ($this->foo) {
echo $indent . 'bar= myPost';
} else {
echo $indent . 'baz= myNav';
}
?>
footer
+footerContent
And if your Pug is processed on the server then you'd also include a Pug-processing step, for instance if you use Apache you could use
mod_ext_filter configured in such fashion with pug-cli installed:
ExtFilterDefine pug-to-html mode=output intype=text/pug outtype=text/html \
cmd="pug"
<Location />
SetOutputFilter pug-to-html
</Location>
Have you checked out the pug-php project? I personally have no experience with this particular module, but it seems to do just what you're trying to accomplish: Being able to use PHP in Pug.
You can use the scape syntax with quotes:
!{'<?php #php code ?>'}
For example:
p Hello !{'<?php echo "My name"; ?>'}
Will render:
<p>Hello <?php echo "My name"; ?></p>
You can test it here: https://pug-demo.herokuapp.com/
There is a well-known and well-maintained Pug processor written natively in PHP. You can use it to process your Pug files into HTML, just like the original Pug, with the advantage that it allows you to embed and use PHP code in your Pug file with ease. If you're working with PHP inside Pug, check it out:
Phug - the Pug template engine for PHP
p Hello !{'<?php echo "My name"; ?>'}
works but
link(href="../assets/css/style.css?v=!{'<?=$AppsVersion?>'}" rel="stylesheet" type="text/css")
don't work
Ay guys,
I do know two possibilites to display PHP in HTML:
<?php function(); ?> or the shorter method <?= function(); ?>
But I often see something like {METHOD} or {OUTPUT} in the HTML part of bigger scripts f.e.:
<div class="test">{OUTPUT}</div>
In my opinion this is a way tidier. Could somebody tell me more about this?
I have used php to generate html using the echo function and have used php inside html too.(If this clarifies your doubt in anyway)
echo $projectname; inside html file tags
echo the html file
Cheers :)
When echoing data in HTML without a template engine, short tags are preferred as they look cleaner, and are easier to read. They're great when using control structures too: http://php.net/manual/en/control-structures.alternative-syntax.php
For short tags to work short_open_tag needs to be enabled.
The example you shown with the curly brackets is usually specific to a template engine such as Twig.
you can use this method only with the function ECHO with double quotes :
1 - this works
$name = 'Mark';
echo "<div>GoodMorning {$name}</div>";
2 - this does not work
$name = 'Mark';
echo '<div>GoodMorning {$name}</div>';
Is there any difference between the following 2?
1 separate php code from html
<html>
<body>
<?php // php code 1 ... ?>
<div> ... </div>
<?php // php code 2 ... ?>
<div> ... </div>
<?php // php code 3 ... ?>
</body>
</html>
2 everything inside php
<?php
echo "<html>";
ehco "<body>";
// php code 1 ...
echo "<div> ... </div>";
// php code 2 ...
echo "<div> ... </div>";
// php code 3 ...
echo "</body>";
echo "</html>";
?>
Which is faster?
It is not the way to increase the speed. If you are not satisfied with your app performance - take profiler and find the slowest part. After that - optimize that slowest part.
The way "I optimize the things that it is easy to optimize" is always the worst.
The first one is faster because interpreter will take care only about the code inside the tags.
The second one should not be use, double quotes are interpreted to see if there is a variable inside. You should always use simple quote when you don't want string to be interpreted.
The usual usage is what you listed in the first form, although in some cases, such as a helper function to generate <a href="..." ... >link word</a>, then you will generate HTML inside PHP code. Or if you have a function that generates a table, or an ul with many li printed out with data from inside an array or hash.
Whatever performance difference you'll find is moot and academic. Choose the first form. The second form isn't future-proof. A simple change in the layout of the HTML page will require a software engineer. The first will just require a creative designer.
With an opcode cache installed on the server (see: APC, eAccelerator), it doesn't matter either way, as the page only has to be interpreted the first time it's accessed.
Performance:
Perhaps the 2nd example would be slightly slower because it does more function calls & also when a string is inside double quotes then the interpreter will look for variables to substitute and escape sequences, eg. \n
PHP blocks also need to be parsed. This may be irrelevant is your script is pre-compiled / running on an accelerator.
Formatting:
1st example will produce HTML code automatically formatted with indentation.
The 2nd example will produce code that's all on one line. Not really an issue as this can be corrected.
Readability:
Perhaps the first example is more readable. Eg. IDE can highlight syntax for HTML and separately for PHP
Others:
2nd example would probably be more preferred choice if the code is in a framework and markup gets extracted in to smaller function(s), sub-classed, etc?
What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.