PHP automatically pre- and append dynamic content to output - php

Is there a way to automatically include content before and after the actual output of a file?
Why? For example to use this to include everything up to the main content (dynamcally generated HTML, head, opening tags...) and after the file runs, automatically close everything up again.
I know of the ob_start approach, but I'm not sure if dynamically generated content is easy to include that way:
<?php
function bootstrap_page($content) {
return "text before" . $content . "text after";
}
ob_start(bootstrap_page);
?>
But then, ob cannot be used to capture the output of an include within the callback, AFAIK. So that makes it hard to easily pre- and append something dynamically generated. I could use long strings in the callback function to get a static version working - but is there a way to do this more seamlessly?
In other words I'm basically trying to include a php file before and one after any (other) file I need and that - if possible reduced to a function call at the start of a given file.
The functionality I'm looking for would transform this:
<?php
bootstrap_this();
?>
<p>Lorem ipsum</p>
before.php:
<!DOCTYPE html>
<html>
<?php include('head.php'); ?>
<body>
<?php if(somecondition) { ?>
<h1>Hello, World!</h1>
<?php } ?>
after.php:
</body>
</html>
Into something like this:
<?php
include 'before.php';
?>
<p>Lorem ipsum</p>
<?php
include 'after.php';
?>
And in the end into:
<!DOCTYPE html>
<html>
<?php include('head.php'); ?>
<body>
<?php if(somecondition) { ?>
<h1>Hello, World!</h1>
<?php } ?>
<p>Lorem ipsum</p>
</body>
</html>

Isn't that what output buffering is for?
<?php
// Start Buffer
ob_start();
// Include before
include 'before.php';
?>
<p>Lorem ipsum</p>
<?php
// Include after
include 'after.php';
// Get buffered output
$page = ob_get_clean();
echo $page;
?>

But then, ob cannot be used to capture the output of an include within the callback, AFAIK
AFAYK ? Would it be hard to test? As long as the include is after ob_start() and the code does not explicitly call ob_flush() before you choose to do so, then it will capture the output.
I'm basically trying to include a php file before and one after any (other) file I need
That implies some set sort of controlling script which calls the pre-oinclude, the main content and the post-include.
That would be OK if HTML (not true, I'll come back to that) did not have a defined root which should be explicitly declared. And you have the issue HTTP also has a structure which you risk subverting here - headers come before content. But leaving those aside for now, HTML requires a nested structure. All tags should be closed. Opening and closing tags in different files is messy and bad practice.
There are a whole lot technologies which provide the end result you appear to be looking for - ESI, templating and front-controller patterns all provide this in a much more structured way.

I'm not sure I see the usage of this or if I understood this correct, but if I understood it correctly you're looking for something like this:
<?php
function dynamice_include($before, $content, $after) {
$dynamic_content = '';
$dynamic_content .= include $before . '.php';
$dynamic_content .= $content;
$dynamic_content .= include $after . '.php';
return $dynamic_content;
}
Usage:
$content = dynamice_include('before', 'Hello I am really cool','after');
echo $content;
In before.php and after.php a return would be required, e.g.
before.php
<?php
return "wow before";
after.php
<?php
return "wow after";
and the result would be:
wow beforeHello I am really coolwow after
UPDATE:
It seems it more something like this you're looking for. output-buffers are the only way AFAIK to achieve this.
This code is not optimized at all... (I just show the concept here)
<?php
function dynamice_include($before, $content, $after) {
$dynamic_content = '';
ob_start();
include $before . '.php';
$dynamic_content .= ob_get_contents();
ob_end_clean();
ob_start();
include $content . '.php';
$dynamic_content .= ob_get_contents();
ob_end_clean();
ob_start();
include $after . '.php';
$dynamic_content .= ob_get_contents();
ob_end_clean();
return $dynamic_content;
}
$content = dynamice_include('before', 'dytest','after');
echo $content;
As other stated though - it's a lot of platforms, frameworks, template engines out there that could solve this issue. You will have do ob_start() and ob_clean within the current files content for this to work.
UPDATE2:
In this case I fetch current files output buffer as content.
<?php
function dynamice_include($before, $content, $after) {
$dynamic_content = '';
ob_start();
include $before . '.php';
$dynamic_content .= ob_get_contents();
ob_end_clean();
$dynamic_content .= $content;
ob_start();
include $after . '.php';
$dynamic_content .= ob_get_contents();
ob_end_clean();
return $dynamic_content;
}
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
feelings
</body>
</html>
<?php
$content = ob_get_contents();
ob_end_clean();
$content = dynamice_include('before', $content, 'after');
echo $content;
?>

Thanks to the help of #bestprogrammerintheworld, I came up with this:
function use_template($before = 'pre', $after = 'post') {
ob_start();
include $before . '.php';
$pre = ob_get_contents();
ob_end_clean();
ob_start();
include $after . '.php';
$post = ob_get_contents();
ob_end_clean();
$bootstrap_page = function ($content) use ($pre, $post) {
return $pre . $content . $post;
};
ob_start($bootstrap_page);
}
If this function is called a the beginning of a php file, the outputs of before.php and after.php get stored and bound to the callback. Then, after all the main output is read, everything is pieced together. No code at the end of the file required.
Since ob cannot be run within the callback, bootstrap_page, it must be run beforehand to capture the other files first.

Related

php load up a .php page and replace variable, and then store the output

I would like to load different .php page (the .php contain html and some php variable need to be replaced.
For example:
load.php
$output = '';
load the test.php and replace that $this->name with value.
store the html to $output
load the test1.php and replace that $this->name with value.
append to the previous $output variable
so at the end i would have a $output variable have all the updated html
Any suggestion is appreciated.
test.php
>
<html>
<?php echo $this->name; ?>
</html>
test1.php
>
<html>
<?php echo $this->address; ?>
</html>
You likely want to use output buffering with a require or include statement:
ob_start();
require('load.php');
$output = ob_get_contents();
ob_end_clean();
$output should contain the contents of load.php with any variables processed.
To process multiple files (or anything else) just run it all between ob_start() and the last two lines, so you could grab two files like so:
ob_start();
require('test.php');
require('test1.php');
$output = ob_get_contents();
ob_end_clean();

How do I populate a variable using a function?

I have the code below on a page basically what I'm trying to do is fill $content variable using the function pagecontent. Anything inside pagecontent function should be added to the $content variable and then my theme system will take that $content and put it in theme. From the answers below it seems you guys think I want the html and php inside the actual function I don't.
This function below is for pagecontent and is what I'm currently trying to use to populate $content.
function pagecontent()
{
return $pagecontent;
}
<?php
//starts the pagecontent and anything inside should be inside the variable is what I want
$content = pagecontent() {
?>
I want anything is this area whether it be PHP or HTML added to $content using pagecontent() function above.
<?php
}///this ends pagecontent
echo functional($content, 'Home');
?>
I think you're looking for output buffering.
<?
// Start output buffering
ob_start();
?> Do all your text here
<? echo 'Or even PHP output ?>
And some more, including <b>HTML</b>
<?
// Get the buffered content into your variable
$content = ob_get_contents();
// Clear the buffer.
ob_get_clean();
// Feed $content to whatever template engine.
echo functional($content, 'Home');
As you are obviously a beginner here's a much simplified, working version to get you started.
function pageContent()
{
$html = '<h1>Added from pageContent function</h1>';
$html .= '<p>Funky eh?</p>';
return $html;
}
$content = pageContent();
echo $content;
The rest of the code you post is superfluous to your problem. Get the bare minimum working first then move on from there.
Way 1:
function page_content(){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
$content .= page_content();
Way 2:
function page_content( & $content ){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
$content .= $buffer;
}
$content = '';
page_content( $content );
Way 3:
function echo_page_content( $name = 'John Doe' ){
return <<<END
<h1>Hello $name!</h1>
END;
}
echo_page_content( );

How to change title of the page after including header.php?

page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
<title><?php echo $title; ?></title>
I want my title to be set after including the header file. Is it possible to do this?
expanding on Dainis Abols answer, and your question on output handling,
consider the following:
your header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
and that should do it.
EDIT
I believe Guy's idea works better since it gives you a default if you need it, IE:
The title is now <title>Backup Title</title>
Code is now:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
1. Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
2. Add following code into header.php
<title><?php echo $title; ?></title>
What you can do is, you store the output in a variable like:
header.php
<?php
$output = '<html><title>%TITLE%</title><body>';
?>
PS: You need to remove all echos/prints etc so that all possible output is stored in the $output variable.
This can be easely done, by defining $output = ''; at the start of the file and then find/replace echo to $output .=.
And then replace the %TITLE% to what you need:
<?php
include("header.php");
$title = "TITLE";
$output = str_replace('%TITLE%', $title, $output);
echo $output;
?>
Another way is using javascript in your code, instead of:
<title><?php echo $title; ?></title>
Put this in there:
<script type="text/javascript">
document.title = "<?=$title;?>"
</script>
Or jQuery, if you prefer:
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "<?=$title;?>");
});
</script>
Expanding a little on we.mamat's answer,
you could use a preg_replace instead of the simple replace and remove the need for a %title% altogether. Something like this:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
you can set using JavaScript
<script language="javascript">
document.title = "The new title goes here.";
</script>
Add this code on top your page
<?php
$title="This is the new page title";
?>
Add this code on your Template header file (include)
<title><?php echo $title; ?></title>
It's very easy.
Put this code in header.php
<?
$sitename = 'Your Site Name'
$pagetitle;
if(isset($pagetitle)){
echo "<title>$pagetitle." | ". $sitename</title>";
}
else {
echo "<title>$sitename</title>";
}
?>
Then in the page put there :
<?
$pagetitle = 'Sign up'
include "header.php";
?>
So if you are on Index.php , The title is Your Site Name.
And for example if you are on sign up page , The title is Sign up | Your Site Name
Every Simple just using a function , I created it .
<?
function change_meta_tags($title,$description,$keywords){
// This function made by Jamil Hammash
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/","<meta name='description' content='(.*)'>","<meta name='keywords' content='(.*)'>");
$replacements = array("<title>$title</title>","meta name='description' content='$description'","meta name='keywords' content='$keywords'");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
First of all you must create function.php file and put this function inside ,then make require under the MetaTags in Header.php .
To use this function change_meta_tags("NEW TITLE","NEW DESCRIPTION",NEW KEYWORDS); .
Don't use this function in Header.php !! just with another pages .
Use a jQuery function like this:
$("title").html('your title');

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?

For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.
snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:
<article>
<h1>{$headline}</h1>
<p>${$body}</p>
</article>
I'd like to be able to return this code from a function, along the lines of this:
function writeArticle($headline, $body){
return "contents of snippet.php using the variables passed in to the function"
}
I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.
One method is using file_get_contents and str_replace
HTML:
<article>
<h1>[-HEADLINE-]</h1>
<p>[-BODY-]</p>
</article>
PHP:
function writeArticle($headline,$body){
$content = file_get_contents("[add your html directory here]/file.html",true);
$content = str_replace("[-HEADLINE-]",$headline,$content);
$content = str_replace("[-BODY-]",$body,$content);
echo $content;
}
You can use output buffering and include the file so the PHP variables get evaluated. However, since you are not using <?php PHP tags ?> you will need to wrap it in HEREDOC format (http://php.net/manual/en/language.types.string.php). Scroll down to Heredoc on the page.
snippet.php
$output = <<<HEREDOC
<article>
<h1>{$headline}</h1>
<p>{$body}</p>
</article>
HEREDOC;
function writeArticle($headline, $body){
ob_start();
include('snippet.php');
$snippet = ob_get_clean();
return $snippet
}
You could do this:
HTML DOCUMENT
Include('blockClass.php');
$block = new blockClass();
echo $bl = $block->block($headline, $body);
CLASS DOCUMENT
class blockClass{
function block($headline, $body){
$var ='<article>
<h1>' . $headline . '</h1>
<p>' . $body . '</p>
</article>';
return $var;
}
}
I had the same question and ended up solving it like this. I feel like this is the cleanest approach. Just turn php on and off within the function.
<?php
function writeArticle($headline, $body){
?>
<article>
<h1><?php echo $headline; ?></h1>
<p><?php echo $body; ?></p>
</article>
<?php
}
?>
writeArticle('foo', 'bar');

Include PHP file as string

is it possible to make something like this?
// file.php
$string = require('otherfile.php');
echo $string;
// otherfile.php
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<?php require 'body.php';?>
</body>
</html>
// body.php
<p>Lorem ipsum something</p>
And get this output?
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<p>Lorem ipsum something</p>
</body>
</html>
I know that code won't work, but I hope you understand what I mean.
file.php
ob_start();
include 'otherfile.php';
$string = ob_get_clean();
$string = file_get_contents('otherfile.php',TRUE);
echo $string
Use of the TRUE argument for file_get_contents() means it will search using the include path, like a normal include or require
Another cool thing to know, but SmokeyPHP's answer might be better:
<?php
$var = require 'myfile.php';
myfile.php:
<?php
return 'mystring';
Yes, you can use a return statement in a file, and requires and includes will return the returned value, but you would have to modify the file to say something more like
<?php
return '<p>Lorem ipsum something</p>';
?>
check example #5 under include documentation
http://www.php.net/manual/en/function.include.php
I need a solution for Joomla and dompdf and I found this solution
ob_start();
require_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . 'file.php';
$html = ob_get_clean();
only with require_once can use all functions from Joomla at the loaded script.
The file.php is a .html file renamed to .php and where added php code.

Categories