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.
Related
I know how to insert html code in php using print <<<HERE HERE; construction. It means I can insert a link to css file. But is it possible to insert css code itself?
There are a couple of ways you can achieve this.
Lets say you have an anchor tag My Href and you want to add CSS to it based on certain instances.
You can easily echo that css into the anchor element like so:
<a <?php echo 'style="float: left;"'; ?> href="..">My Href</a>
The output would be:
<a style="float: left" href="...">My Href</a>
You can do this with almost any HTML element.
Now let's say you have a predefined CSS class you would like to echo into an anchor tag element.
Let's say you have this CSS class in your stylesheet:
.floatLeft {
float: left;
}
You can simply echo that class into the anchor element like so:
My Href
Which the output of that would be:
My Href
Yes. It is possible.
There's actually two different ways.
Method 1: Inject PHP into your actual CSS. This is done by making your file .php, using regular HTML and CSS, and then doing as such:
.someclass {
/* Some code */
<?php // Whatever you wanna inject
?>
I have performed this many times, and no one knows. It may not be the most efficent way, but it's also sometimes better than doing...
Method 2: Escape your quotes and lines.
Use:
echo("/* Your css code here */ \ (to escape the line return
/* Whenever there is a quote, make sure to do the following: \" ");
If you don't escape the quote, PHP will think you're ending the string. That's bad, because the rest of your text gets ignored.
ADDITIONAL NOTE: You don't have to use print for echoing HTML. Echo works too.
Yes, you can easily do that. You can either do it in the CSS file like 'ilarsona' said, or you can do it in the HTML file itself.
For example:
<!DOCTYPE html>
<html>
<head>
<title>The Title</title>
<style>
p {<?php *Insert dynamic styles here* ?>};
</style>
</head>
<body>
<div style=<?php *Insert styles here* ?>> </div>
</body>
</html>
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'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;
?>
Well most is in the title. I wonder if it's supposed to be that way or i can do the same without an if(1) condition I'm doing this because my website pages are all as php includes.
Thank you all
Answer retained:
Okay basically the way to do it is simply to include('file.php') as it will be considered out of the current <?php ?> environment.
Putting
<?php if(1): ?>
...
<?php endif; ?>
around your HTML code in a PHP file will have no effect on the result. You will still be able to include the file without it.
You can think of it like the "default mode" for a PHP file is that it contains HTML content. You only need to add <?php ?> tags if you want to add PHP code. If you're just putting HTML code in a PHP file, they're unnecessary.
The beauty of PHP is that you can move "in" and "out" of PHP very easily. You can do the following without issues:
<?PHP
if(whatever) {
?>
your HTML
<?php
include('whatever.php');
?>
more HTML
<?PHP
}
?>
To build on Zak's answer:
You can also use PHP to echo out things that aren't PHP... as long as you quote it appropriately.
<?php
//HTML
while ($x < 5) {
echo "<p> this is html that you can wrap with html tags! </p>";
$x++;
}
//Javascript
echo "<script type='text/javascript'>
some javascript code
</script>"
?>
Although, it's less confusing to just end the php tag to keep things separate.
And you can even use php as you want within html or javascript as long as you put the tags, and as long as the file is saved as a .php file (so PHP can be processed on the server).
Ex:
<script type="text/javascript">
//set a javascript image array to a php value
var imgArray = [<?php echo implode(',', getImages()) ?>];
</script>
But if you want to do this the other way around (IE, assign a browser-compiled value, such as a javascript value to a php value), you'll need to use AJAX.
How can I replace the text on the active document body on a PHP file on code execution?
Do I have to import a file, replace text on it and then echo it or can I just manipulate the document I run the PHP script on?
I am trying to use templates for easier HTML editing like :usernamecomeshere: and then replacing that :usernamecomeshere: with the actual value. I am wondering If I can do it on one file only instead of loading a file and then displaying it.
If I'm getting your question correctly, you don't need to important a file and echo the document. You can directly manipulate the document itself. For example, in the below sample, you can directly echo the contents of $username in a way that's interspersed with HTML code.
index.php
<?php
// handle code to login
$username = "David";
?>
<html>
<body>
<p>Hello, your username is <?php echo $username ?></p>
</body>
</html>
Worth pointing out is that PHP itself is a templating engine. If you want to replace text, you can do it using PHP such as:
<?php
$user = 'Ugur';
?>
<html><head></head>
<body>
<h1>Hello <?php echo $user; ?></h1>
</body>
</html>
Beyond this sort of simple usage, you may want to look at various template engines, which allow you to do much more elegant things, but are more complex. Take a look at mustache, perhaps?
If you're trying to make these modifications after the page has loaded, remember that PHP runs on the server-side, not the user-side. For that, you need Javascript.
you'll want to look up str_replace() on google. You can search an entire string and replace specified keywords simply.