PHP buffer included file as anonymous function - php

I have a kind of template file that may be called filename.php:
<h1>
<?= $test . ' world'; ?>
</h1>
<p>
Some text
</p>
Then I have a function in an index.php file that looks like this?
<?php
function test($args) {
$test = $args;
include 'filename.php';
}
test('Hello');
test('Hello');
test('Hello');
This code works. It output the included data 3 times.
I can also use output buffering to get the output as a string if I want. However, that's not exactly what I want.
Problem
I can't figure out a way to only need to include the filename.php one time (now it's loaded 3 times). Because it accepts arguments it can't be returned as string. It needs to be returned as an anonymous function, I guess. Then I could buffer my template and still use it with new values.
Any creative ideas are welcome.

Related

How to embed include file within data that a variable stores?

I have HTML content in the variable $detail and I want to "embed" PHP files there.
Note: The variable "$detail" gets stores the information from a query to the database.
This variable $detail has paragraphs "<p> </p>" in those paragraphs I need to be able to "embed" PHP files, for example, in the second paragraph, embed "file1.php" the other file in the fifth paragraph.
It is important that it is in PHP
I had already done something similar but with JAVASCRIPT but when the browser has JAVASCRIPT debugging deactivated everything is out of order, that's why I'm looking for some way to use it with PHP
Example:
include 'file1.php';
include 'file2.php';
//They must be included or embedded in the $detail variable, the first file, in the third paragraph, and the second file, in the seventh paragraph
echo $detail;
You can use output buffering to get file1.php and file2.php, additionally with preg_replace() like:
$detail = "
<p>1</p>
<p>...</p>
<p>3</p>
<p>4</p>
<p>...</p>
<p>6</p>";
ob_start();
include 'file1.php';
$file1 = ob_get_clean();
ob_start();
include 'file2.php';
$file2 = ob_get_clean();
$detail = preg_replace('/^(.*<p>.*<p>).*(<\/p>.*<p>.*<p>.*<p>).*(<\/p>.*)$/Us', "\${1}{$file1}\${2}{$file2}\${3}", $detail);
echo $detail;
However you should check your business logic or use a PHP template engine, like Smarty as #kiko-software said earlier.

str_replace (or another option) for replacing content located inside a php document

I'm attempting to make a template file for a CMS that I'm making where the template file can contain variables like {username} as regular text that get replaced when the page gets included on the index.php page.
Example:
Index Page:
<?php include('templates/123/index.php'); ?>
templates/123/index.php page
<?php include('header.php'); ?>
Welcome {username}
<?php include('footer.php'); ?>
I've tried several methods; however, always run into problems because the page I'm trying to change the content on includes PHP code. Every method I try either 1) messes up because the opening and closing of PHP tags within the document OR 2) just echoes out the PHP code in the document. Is there any way that I can still achieve this? Maybe even with a class of some kind? I just want to be able to achieve this safely.
I will also be using this to where custom variables like {content1} get replaces with a php code that will be ioncubed that retrieves the data from database for content located in column1, same with {column2} {column3} and {column4}. I'm just trying to make the creation of templates extremely easy. (so I'd like to make the code work for that as well)
My preferred method of doing stuff like this involves starting my code with:
ob_start(function($c) {
$replacements = array(
"username"=>"Kolink",
"rank"=>"Awesome"
);
return preg_replace_callback("/{(\w+)}/",function($m) use ($replacements) {
return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
},$c);
});
Two steps I suggest
Load the result of your file "templates/123/index.php" into a variable. see this link for how to do it assign output of execution of PHP script to a variable?
use strtr() function to replace your placeholder i.e {username} with actual values
I think this will server your needs.

Capture content after function is called

Is it possible (in PHP) to call a function that triggers some capturing process so all HTML output after that function is captured up until an ending function? For example, some profiling applications do very similar procedures to this, and with functions such as ob_start(), it seems logical to me.
Example of concept:
<?php beginSection("hello"); ?>
<b>Hi there!</b>
<?php endSecton("hello"); ?>
<!-- Section "hello" now contains "<b>Hi there!</b>" -->
The way output buffering works does not allow you do this in a named fashion - ob_start and its friends stack on eachother, and unwind in order. You could implement it like this:
<?php ob_start(); ?>
<b>Hi there!</b>
<?php $sections['hello'] = ob_end_clean(); ?>
This would answer your question.

Render file with shortcode into a wordpress plugin

I am relatively new to php and wordpress and I would like to know how I can render a php file without the include statement.
For example if I have two files plugin.php and component.php
plugin.php
<?php
add-shortcode('myshortcode', 'myshortcode-func');
function myshortcode-func()
// magic function that loads
$result = LOAD('component.php');
return $result;
}
?>
component.php
<div>
<img scr="<?php getimage() ?>" />
</div>
NB
I don't want to use include because I think it screws the rendering and insert the page in the flow when called.
Thanks for you help !
You can use an output buffer:
function myFunc(){
ob_start();
include('component.php');
return ob_get_clean();
}
How to:
$php = file_get_contents("component.php");
eval($php);
eval is very dangerous though and shouldn't be used in production.
If this is for production, I'd recommend using hooks/filters (see wordpress source code). This lets you execute blocks of code on the fly, but is more constrained.

Can I load a file in PHP as a string with inline variables?

I've got a simple (but not tiny) template for some HTML, complete with inline variables. I'd like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?
Eg:
$thing="complete sentence";
$test=<<<END
This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.
What I want is something like this:
// "test.html"
<html>
<body>
<p>This will get parsed as a $thing.</p>
</body>
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.html");
echo $test; // This will get parsed as a complete sentence.
How do I achieve this, preferably without a templating library?
<?php
$thing="complete sentence";
$test=file_get_contents("test.php");
echo preg_replace_callback('#\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)#','changeVariables',$test);
function changeVariables($matches)
{
return $GLOBALS[$matches[1]];
}
This code uses preg_replace_callback to check what is variable. But, because we are in function, we cannot directly access script variables. We have to use $_GLOBALS variable which contains every script variable. $matches[1] contains name of matched variable.
Something like this should work...
// "test.php"
This will get parsed as a %s.
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.php");
printf($test, $thing);
You can use include to simply load the file as if it were part of the calling code.
include("included_file.php");
If you cannot include for some reason, you can read the file contents and eval it.
$content = file_get_contents("included_file.php");
eval($content);
UPDATE:
As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include can work. Your test.html should have this content:
<html>
<body>
<p>This will get parsed as a <?= $thing ?>.</p>
</body>
And eval would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.

Categories