i have just learned about include() function in php, which enables to include whole document into another document. i was wondering how to do the same, if i would like to include not a whole document, but only a snippet of code, from one document into another one.
You can do it with 2 approach:
You can go with #blckbird idea and put your code in a new file and just include it.
You can create a file containing a method foo(), with your snip code. include the file and just call that foo().
Exmple:
// helper.php - contain your snip/reusable code
<?php
function startPage($title){
print '
<!DOCTYPE html>
<html>
<head>
<title>'.$title.'</title>
</head>
<body>';
}
function endPage(){
print '
</body>
</html>';'
}
?>
Now your main file include helper.php and call the method you want.
// main.php
<?php
include("helper.php");
startPage("My Title");
// do your stuff/coding here
endPage();
?>
hope it helps a bit.
Related
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.
At the very top of my page/site, before <!doctype html> etc., I load my classes with spl_autoload_register().
One of the classes is site, and inside this class I have a static function:
<?php
/**
* A fast and easy way to include content to a page...
* "dir_pages_contents" is a defined constant with the path to the content files
*/
public static function include_content($content_name){
if(file_exists(dir_pages_contents.$content_name.'.cont.php')){
include dir_pages_contents.$content_name.'.cont.php';
} else {
/* echo an error message */
}
}
?>
I was hoping to do something like this i practice:
create a new document with some content and save it with the extension .cont.php into a folder specified for page contents.
Then; On the page where I want this content to be displayed - I do:
site::include_content('test_doc');
This almost works; The document, or content, is included and displayed.
But it seems like it is included where the class is - at the very top where the class is - because PHP-variables set outside of this document is not available within the document at all.
Here's a illustration of the setup:
test_doc.cont.php
<?=$hello?>
index.php
<!-- PHP-classes are included here -->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php $hello = 'Im outside...'; ?>
<!-- this includes the document, but the variable $hello is not -->
<?=site::include_content('test_doc')?>
<!-- this works perfectly -->
<?php include dir_pages_contents.'test_doc.cont.php; ?>
</body>
</html>
The inclusion of a separate file, or document, is done immediately when the include-statement is read by the script i guess? but not displayed until futher down the script where the function was called?
Any suggestion for another way to accomplish this?
I'm not looking for any MVC or other PHP-framework.
EDIT:
user1612290 pointed out to me that the include-statement within my include_content-function only uses the variable scope of my function - meaning that any variables decleared outside my include_content is not passed to the include directive unless I make them global.
It was also suggested that I could pass an array of named keys=>$variables into my function and use extract() on them to make them available.
This is what I came up with:
- added $arr
public static function include_content($content_name,$arr){
if(file_exists(dir_pages_contents.$content_name.'.cont.php')){
if (is_array($arr)){extract($arr);}
include dir_pages_contents.$content_name.'.cont.php';
} else {
/* echo an error message */
}
}
Now I'm able to do this:
<?=site::include_content('test_doc',array('hello'=>$hello))?>
Allthoug I'm not happy with this solution, I now have the variables accessable within the included document - so I'm closer than I was an hour ago :)
Any easier way?
Can somebody tell me to run php inside an html file that is opened inside an php file.
Its like this.
I have an HTML file like this:
<html>
<head>
<title></title>
</head>
<body>
<h1>Some heading</h1>
<? $sometekst_variable ?>
</body>
</html>
What i whant is to open the file inside my php function and to let the function run the php inside the file. The php variable will be set inside the function where the file is read.
Is there a way to do this?
Use an include. In your top file, do something like
include('otherfile.php');
You can do it via require 'that_template_file';
If you want to catch the html output of that file (e.g. run it, but not print it to the output stream), you can (must) use output buffers, like so:
<?php
function render($tpl) {
// this way it would print out everything to the output, without a chance to grab that
require $tpl;
// OR do it like this:
ob_start();
require $tpl;
$parsed_result = ob_get_contents();
// now you can print out the result or do something else with it...
echo $parsed_result;
// or return it
return $parsed_result;
}
render('template.ext.php'); // note, it doesn't have to be .php... it can be anything
Also note that you can nest calls to ob_start, so you can nest the render function.
Like so:
index.php:
<?php render('template.inc.php'); ?>
template.inc.php:
<div><?php render('header.inc.php'); ?></div>
and so on.
Say I have a the following files
Example 1
functions.php
<?php
session_start();
function getSessionData(){
...
// returns array
}
?>
index.php
<?php
session_start();
include("functions.php");
$sessionData = getSessionData();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php print_r($sessionData); ?>
</body>
</html>
Now the index.php includes functions.php. Because I have session_start() in index.php, does this mean it's automatically added in the functions.php (seeing as functions is included in index?)
Im not sure if im making this clear or not.
Example 2
config.php
<?php
$url = "www.example.com";
?>
functions.php
<?php
include("config.php");
function getSomething(){
...
return $url
}
?>
index.php
<?php
include("config.php");
include("functions.php");
$some_var = getSomething();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?=$some_var;?>
</body>
</html>
Now both functions.php AND index.php include config.php...
But because config is already included in index.php...
does this mean it has to be included functions aswel?
I think I've just confused myself tbh:)
Yes. You can think of includes as simply pasting the code in the file where the include statement is.
In example 2, you don't need to include config again in index, as it has already been included in functions (or vice versa) - what you're actually doing there is running the code in config.php twice (which can be prevented by using include_once for example).
The same goes for session_start() in example 1. When index is loaded the following happens:
session_start
include functions.php
session_start (not needed now)
function getSessionData() {..}
(back to index) - call getSessionData()
Also, in your second example, you won't be able to access $url in that function without calling global $url before it (inside the function).
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.