I have one question to ask you.
I have 2 PHP files first one is index.php and another one is body.php
index.php contain HTML template like
<html>
<head>
<title></title>
</head>
<body>
<? include('body.php') ?>
</body>
</html>
and body.php query data from database(such as name, nickname, age).
I need body.php to change tag or add more tag in index.php
How should i do in PHP command?
thanks
In your example, body.php can have any HTML output you need. The output of body.php will be included in your final output.
If you need to make the final output of index.php dependent on the body.php file, (for example to insert a title) you can load your content into variables, which can be outputted later.
<?
include ('body.php');
/* $title and $bodyHTML are set in the include file */
?>
<html>
<head>
<title><? echo $title; ?></title>
</head>
<body>
<? echo $bodyHTML;?>
</body>
</html>
You can use fopen() and fwrite() to modify the content of index.php from body.php (assuming that you have the write permissions, of course).
If you mean change the content while the user is viewing index.php and then change index.php, then that isn't possible without telling the user to "click here and view the new code!" (since at that point, you can no longer use headers to refresh the page).
PHP is not a dynamic content language like, for example, JavaScript.
You can't alter variables in part of the page that has already been output. You can use output buffering to capture the output to that point and then do string substitutions on it
<?php ob_start(); // start buffering output
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
include('body.php');
// Get the contents of the buffer and then clear the buffer
$buffer = ob_get_clean();
// Replace your keyword with a variable loaded from body.php
$buffer = str_replace('%nickname%', $nickname, $buffer);
// output the altered head
echo $buffer;
// Stop buffering and output what we just echoed
ob_end_flush();
?>
</body>
</html>
There are a number of PHP template and theming engines out there that make
doing this kind of thing easier. Smarty is a fairly
popular one. Another one I like is Savant but I'm personally partial to the one I created called Enrober.
write db related stuff in body.php file and call those functions from index.php.
Loop those results and built through related tags and display.
Thats it.........
You could output the entire thing from a php object called domdocument, which allows dynamic creation of html documents.
That way, you could change the tags and their content as dynamically as you want.
Related
I'm looking for advice on the best practice for separating site content up into logical blocks. I want a header and footer that are constant throughout the site, so that if I have several pages of different content, they will all look as below — changes made to the header and footer then update automatically without me having to change each individual page.
<?php
include 'header.php';
?>
<body>
<p>page content here</p>
</body>
<?
include 'footer.php';
?>
The header.php would contain the opening <html>, <head> and static content, and the footer.php would contain any extra static content and the closing </html> tag. So, my question is: Is this a good approach? I'm worried that spreading the <html> tags across multiple files is bad practice. If so, what is the right way to approach this kind of design?
Nope, your approach is wrong.
Here are main faults in your design:
You're assuming that header.php would be called on the every page call. That's wrong.
You're assuming that header.php will always be static. That's wrong.
You forgot to create a template for the page itself.
The main rule everyone have to learn by heart:
Not a single character has to be sent into browser, until all data gets ready.
Why?
it's 2011 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
it's for just 4-page site. Okay. Imagine you've got lucky and got a request for another 4-page site. You will have to change only templates and don't touch engine files. That's really great benefit.
Imagine you're going to make a custom <title> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates.
So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.
An example layout is going to be like this:
.1. page itself.
it outputs nothing but only gather required data and calls a template:
<?php
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "template.php";
?>
.2. template.php which is your main site template,
consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<?php include $tpl ?>
</div>
</body>
</html>
.3. and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<?php foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
<ul>
easy, clean and maintainable.
In building off of Your Common Sense's answer, there's not a good reason to have 2 files for every page. You can easily combine your template (YCS called this .tpl.php) and your actual page into one file.
First, start off with a class that you can expand as your template needs expand:
<?php
#lib/PageTemplate.php
class PageTemplate {
public $PageTitle;
public $ContentHead;
public $ContentBody;
}
Then, make your layout:
<?php
# layout.php
require_once('lib/PageTemplate.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<title><?php if(isset($TPL->PageTitle)) { echo $TPL->PageTitle; } ?></title>
<?php if(isset($TPL->ContentHead)) { include $TPL->ContentHead; } ?>
</head>
<body>
<div id="content">
<?php if(isset($TPL->ContentBody)) { include $TPL->ContentBody; } ?>
</div>
</body>
</html>
And finally, add your page with the body content:
<?php
#Hello.php
require_once('lib/PageTemplate.php');
# trick to execute 1st time, but not 2nd so you don't have an inf loop
if (!isset($TPL)) {
$TPL = new PageTemplate();
$TPL->PageTitle = "My Title";
$TPL->ContentBody = __FILE__;
include "layout.php";
exit;
}
?>
<p><?php echo "Hello!"; ?></p>
This is a basic approach but, yeah, it does work :) I sure would bother with a lot of templating and OOP but you are definitely on the right path
As i can't comment anymore, then i will answer here ;) If he need a custom title then he needs some more advanced functions. So, as i told, this is a basic approach. But in the end, if he really have a static header/footer, and really use them everywhere, well, yes, this is a good way to go.
So ofc you could bother with some advanced headers with parameters you could feed on each page. You could go on a whole MVC stuff. In the end just tell him to use a pre-made framework and stop bothering. How could he learn if you don't let him do some trial and error ?
index.php -- includes header, footer, and content based on REQUEST variable.
header.php -- header content
footer.php -- footer content
content1.php, content2.php, etc.
index.php:
<?php
include ('header.php');
// VERY IMPORTANT - do not use the GET variable directly like this
// make sure to filter it through a white-list
include(basename($_GET['page']).'.php');
include ('footer.php');
?>
if you want the URL to go www.domain.com/pagename where the page you're trying to load into index.php is "pagename", use HTACCESS and do some URL Rewriting: http://corz.org/serv/tricks/htaccess2.php
I'm using a PHP based front controller pattern such that index.php provides the page structure and template, and all content for each page is in include files within /pages/.
index.php
/pages/home.inc
/pages/about.inc
/pages/contact.inc
The include pages are mostly simple HTML so that clients can edit the pages without having to get into anything too complex.
The problem with this layout is that because all page information is in the page include, the <title> element can't get populated. I could put a $title variable in each include, but it loads after the head, which is too late:
<html>
<head>
<title><?php echo $title; ?></title> #$title is not set yet!
</head>
<body>
<?php include($content); ?> #now $title is set
</body>
</html>
It's important that the content files are self contained and mostly HTML, but with the ability to have PHP code as well, as I mentioned, because customers will be modifying these and adding too much complexity is a problem. Thus, for example, setting up a separate database of page titles won't work because customers won't update the database when they make new pages.
Edit: a typical page include might look like this.
<h1>Welcome</h1>
<p>blah</p>
<?php include("nav.php"); ?>
<p>more blah</p>
<p>more blah</p>
<p>more blah</p>
<?php
$pageJavascript = "alert('js!');";
$pageTitle = "Cyberdyne Welcome Page";
?>
Options:
1: Use output buffering
<?php
ob_start();
include($content);
$body = ob_get_contents();
ob_end_clean();
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $body; ?>
</body>
</html>
Pros:
The browser gets fully rendered page
More SEO-friendly (than the javascript title update)
No JS required
Cons:
Need to buffer all the page in memory
2: Set some kind of general title and update it later with javascript.
<script type="text/javascript">
with(document) {
window.title = <?php echo json_encode($title); ?>;
}
</script>
Pros:
You keep the same kind of flow You use now.
Cons:
Not SEO friendly
Requires javascript use
If there is a assumption the title is always on the first line:
"My page Title";
$filename = '/pages/home.inc';
$fileLines = file($filename, FILE_SKIP_EMPTY_LINES);
$title = yourFunctionThatStripsKomma($fileLines[0]);
Only bad thing is, is that you have to be sure the first line has the title.
I am looking for a simple and effective way to create a pure html file based off a php file. For instance, in template.php below the php would be inserting various portions of the page. I want to save the page then as html removing all php code and leaving what was inserted by it... hopefully that makes sense... the output of template.php would be a better way to say it I guess.
First, I do not know if something like this is possible. Second, is this the best way to go about something like this?
Before anyone starts screaming about security there will be ZERO user submitted / form submitted variables in this page. My goal is to create a report from database values with the template which the user can then view/print/save off the server as pure html. There will be no images only inline css.
EDIT :
This html only output of template.php needs to be saved on the server as its own file. The reason for the php 'template' is because I will be creating the vast majority of the page with php... but I only want to save its resulting output.
template.php :
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title><?php echo $title; ?></title>
<meta content="<?php echo $desc; ?>" name="description" />
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body>
... further html with php mixed in
</body>
<!-- END BODY -->
</html>
Current solution :
I did some further research and this is acting exactly how I want it to. Comments/suggestions welcome for it.
<?php
ob_start();
require_once('/home/test/public_html/template.php');
if ( ob_get_length() > 0 )
{
$ssReport = ob_get_contents();
file_put_contents('/home/test/public_html/test.html', $ssReport);
}
ob_end_clean();
?>
You can use REGEX (Regular Expressions) to strip out all php-code.
The Expression <\?php.*?\?> can do that for you...
PHP-Example:
$tempateFile = file_get_contents('template.php');
$htmlPlain = preg_replace('/<\?php.*?\?>/si', '', $tempateFile);
If you allow "Shorthand Open Syntax" for php-files <? instead of <?php you should use the pattern <\?(?:php)?.*?\?> which will become preg_replace('/<\?(?:php)?.*?\?>/si', '', $tempateFile);
If you want to take a html-snapshot of your site(s) try this options:
use wget to grab a copy of your website (see wget manual or wget tutorial)
use curl with a script to grab a copy of your website (see curl manual or
curl tutorial
make a php-script which uses file_get_contents($url) to grab outputs of you specific public-available URL and store it with file_put_contents(...) to a html-file.
Where is the right place to include a file when working with HTML and php?
Before the HTML code:
<?php include 'file.php' ?>
<html>
<head>
</head>
<body>
</body>
</html>
In the head tag:
<html>
<head>
<?php include 'file.php' ?>
</head>
<body>
</body>
</html>
In the body tag:
<html>
<head>
</head>
<body>
<?php include 'file.php' ?>
</body>
</html>
Include the file wherever it would otherwise be in the code...
Example:
- If the include is an html form, it would go in the body.
- If the include is a php script to process the form, it would probably go in the head.
If your imported file is just code with no characters outside the PHP blocks then it doesn't matter. I'd personally put it in the top of the file, so that I could use ini_set affecting the whole execution or send headers or cookies.
I you have content to be printed in the file's main code or outside PHP blocks you should put the file where you want the content.
Just noting, if you want keep the main HTML structure static in your main file and still want to print to both <body> and <head> I suggest you do both in functions, add the import to the file top and call the functions to print.
PHP doesn't care where you put it. For purposes of displaying your page, though, it depends on what is is the included file. For example, if file.php contains the body of your table, obviously it should go in the <body> tag.
It depends on your need.
If your file.php file has some global functions that you'd like to access throughout your code, then I would say include it at the top. Additionally, if you're doing anything with the headers in the included file, definitely include it at the top.
However, say your file.php contains a dynamic javascript code (in other words a script that is changed by php depending on the situation), then the header is probably the best location for it, since that is more or less the standard location to place javascript.
Finally, if your file.php is meant to bring in actual html or structure to the file, then definitely include it in the body.
Something basic that i don't understand:
I have header.php with navigation bar for my site. Inside it, there's a <head>...</head> section.
Now, in each other page of my site, I'm using require_once 'header.php' so that each page will show the navigation bar. But, I need also specific <head>...</head> sections to the different page.
For example, in page customers.php, I'm using <script>...</script> to include the jQuery library. I don't need to include it in other pages.
Now, searching the web I see that multiple head tags is wrong syntax.
So, how can anyone:
avoid multiple "head" tags
WHILE
separating his work to different PHP files and including them ?
You have to change your page structure and employ templates.
Instead of loading header at the top of the code, you have to do it at the bottom!
And page code should output not a word, but collect all data in variables.
And only after that output can be started by calling template.
A example layout is going to be like this:
First. page itself.
it outputs nothing but only gather required data and calls a template:
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.php";
include "template.php";
?>
Next, template.php which is your main site template, consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
And, finally, links.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
easy, clean and maintainable.
there are many advantages in such approach:
as requested, you can populate header with actual page-relevant data.
HTTP headers can be sent as well, before any output. It includes cookies, sessions, cache-control and many more.
it's 2011 today. AJAX era. You may wish change your code to return JSONed data instead of whole HTML page. It's going to be easy using such layout.
Imagine you're going to create very similar site with just different design. You will have to change only templates and don't touch engine files. That's really great advantage of using templates.
Here are some simple ways you can look at.
You can have jQuery on the pages
that don't need it; once it's
downloaded it will be cached so it
still wont use more bandwidth.
You can move out the closing </head>
tag from header.php and close the
<head> tag in the page that's including
header.php.
You can include javascript anywhere
on a page, not only in the header.
You can also do something like this.
Before you do require_once 'header.php'; you put a variable called $jquery = true;
In your header.php file you check if $jquery is set to true, if it is, you include jQuery.
in header.php
you can type like this
<head>
<?php echo $script; ?>
</head>
then in your customers.php
you can first assign the variable
$script = '<script>...</script>'
then
require_once 'header.php'
One possible solution.
You create a global variable before including header.php.
You test this variable in header.php.
If it is true, You print script or something. Something like this:
<!-- Fragment of header.php -->
<?php if ($i_want_jquery): ?>
<script ...>
...
</script>
<?php endif; ?>
On the other hand, a template may be a better solution.