Quite simple question i belive. How to print the whole page into variable and then use where i need.
For instance if the code is:
<?php
$arr = array('hello','mate','world');
foreach ($arr as $a) {print "<p>".$a."</p>"; }
?>
Now if we go to that page, we can see an array output, but i would prefer to print the whole page into variable and then generate static page for instance out of that.
Maybe file_get_content or <<<EOT, but the page will get more complicated later so not sure what is the best option.
Not sure about your exact needs but:
ob_start();
require('/path/to/templates/foo.php');
$template = ob_get_contents();
ob_get_clean();
ob_start();
// your code
$var = ob_get_clean();
print $var;
Why don't you use smarty ,
put all HTML in a template , and insert PHP code or variables into it . in the end , using $x=$smarty->fetch('template_name'); you put all the page in the $x variable ...
Related
how can Dynamic this code with php .my address is variable
<?php
$pagecontents = file_get_contents("http://google.com");
$html = htmlentities($pagecontents);
echo $html;
?>
I'm not sure, I understood, what the goal is, but if you want to do the same thing, that you have shown in the question but with multiple sites, then you can do it with a simple loop:
$sites = ["aa.com/a", "aa.com/b"] // array(...) with earlier PHP versions
foreach($sites as $url) {
$pagecontents = file_get_contents($url);
echo htmlentities($pagecontents);
}
If this is not what you are looking for, then please refactor the question, so it clearly explains, what you want to do!
I have a file like this
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
Everything inside the buffer is dynamically made with data from the database.
And inserting php into the database is not an option.
The issue is, I got my output buffer and i want to replace '{replace}' with a working php include, which includes a file that also has some html/php.
So my actual question is: How do i replace a string with working php-code in a output-buffer?
I hope you can help, have used way to much time on this.
Best regards - user2453885
EDIT - 25/11/14
I know wordpress or joomla is using some similar functions, you can write {rate} in your post, and it replaces it with a rating system(some rate-plugin). This is the secret knowledge I desire.
You can use preg_replace_callback and let the callback include the file you want to include and return the output. Or you could replace the placeholders with textual includes, save that as a file and include that file (sort of compile the thing)
For simple text you could do explode (though it's probably not the most efficient for large blocks of text):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
I might be misunderstanding something here, but something simple like this might work?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
You can also use a return statement from within an include file if you wish to remove the output buffer from that task too.
Good luck!
Ty all for some lovely input.
I will try and anwser my own question as clear as I can.
problem: I first thought that I wanted to implement a php-function or include inside a buffer. This however is not what I wanted, and is not intended.
Solution: Callback function with my desired content. By using the function preg_replace_callback(), I could find the text I wanted to replace in my buffer and then replace it with whatever the callback(function) would return.
The callback then included the necessary files/.classes and used the functions with written content in it.
Tell me if you did not understand, or want to elaborate/tell more about my solution.
im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require inside my page.
Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.
Is there any way to evaluate the require and concatenate its result to my strings?
Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.
thanks for all your help!!! =)
Try the ob_...() family of functions. For example:
<?php
function f(){
echo 'foo';
}
//start buffering output. now output will be sent to an internal buffer instead of to the browser.
ob_start();
//call a function that echos some stuff
f();
//save the current buffer contents to a variable
$foo = ob_get_clean();
echo 'bar';
echo $foo;
//result: barfoo
?>
If you want to put the echo'd result of an include into a variable, you could do something like this:
//untested
function get_include($file){
ob_start();
include($file);
return ob_get_clean();
}
or if you want to put the echo'd result of a function call into a variable, you could do something like this:
//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
$args = func_get_args();
shift($args);
ob_start();
call_user_func_array($function,$args);
return ob_get_clean();
}
Depending on how the other file works...
If the other file can be changed to return a value, then you should use:
$content = require 'otherfile';
If the other file simply uses echo or some other way to print directly, use:
ob_start();
require 'otherfile';
$content = ob_get_clean();
You can receive string with include or require but you have to update those files before including to add return statement.
the file to be included should return result like this
<?php
$var = 'PHP';
return $var;
?>
and you can receive the $var data by including that file
$foo = include 'file.php';
echo $foo; // will print PHP
Documentation section
I am trying to keep my code clean break up some of it into files (kind of like libraries). But some of those files are going to need to run PHP.
So what I want to do is something like:
$include = include("file/path/include.php");
$array[] = array(key => $include);
include("template.php");
Than in template.php I would have:
foreach($array as $a){
echo $a['key'];
}
So I want to store what happens after the php runs in a variable to pass on later.
Using file_get_contents doesn't run the php it stores it as a string so are there any options for this or am I out of luck?
UPDATE:
So like:
function CreateOutput($filename) {
if(is_file($filename)){
file_get_contents($filename);
}
return $output;
}
Or did you mean create a function for each file?
It seems you need to use Output Buffering Control -- see especially the ob_start() and ob_get_clean() functions.
Using output buffering will allow you to redirect standard output to memory, instead of sending it to the browser.
Here's a quick example :
// Activate output buffering => all that's echoed after goes to memory
ob_start();
// do some echoing -- that will go to the buffer
echo "hello %MARKER% !!!";
// get what was echoed to memory, and disables output buffering
$str = ob_get_clean();
// $str now contains what whas previously echoed
// you can work on $str
$new_str = str_replace('%MARKER%', 'World', $str);
// echo to the standard output (browser)
echo $new_str;
And the output you'll get is :
hello World !!!
How does your file/path/include.php look like?
You would have to call file_get_contents over http to get the output of it, e.g.
$str = file_get_contents('http://server.tld/file/path/include.php');
It would be better to modify your file to output some text via a function:
<?php
function CreateOutput() {
// ...
return $output;
}
?>
Than after including it, call the function to get the output.
include("file/path/include.php");
$array[] = array(key => CreateOutput());
I have this code:
$layout_template = template_get("Layout");
$output_template = template_get("Homepage");
$box = box("Test","Test","Test");
eval("\$output = \"$layout_template\";");
echo $output;
In the $template_layout variable is a call for the
variable $output_template, so then the script moves onto the $output_template variable
But it doesn't go any further, inside the $output_template is a call to the variable $box, but it doesn't go any further than one level
I would never want nested eval(), and especially not in any recursive logic. Bad news. Use PHP's Include instead. IIRC eval() creates a new execution context, with overhead whereas include() doesn't.
If you have buffers such as:
<h1><?php echo $myCMS['title']; ?></h1>
I sometimes have files like Index.tpl such as above that access an associative array like this, then you just do in your class:
<?php
class TemplateEngine {
...
public function setvar($name, $val)
{
$this->varTable[$name]=make_safe($val);
}
....
/* Get contents of file through include() into a variable */
public function render( $moreVars )
{
flush();
ob_start();
include('file.php');
$contents = ob_get_clean();
/* $contents contains an eval()-like processed string */
...
Checkout ob_start() and other output buffer controls
If you do use eval() or any kind of user data inclusion, be super safe about sanitizing inputs for bad code.
It looks like you are writing a combined widget/template system of some kind. Write your widgets (views) as classes and allow them to be used in existing template systems. Keep things generic with $myWidget->render($model) and so on.
I saw this on the PHP doc-user-comments-thingy and it seems like a bad idea:
<?php
$var = 'dynamic content';
echo eval('?>' . file_get_contents('template.phtml') . '<?');
?>
Perhaps someone can enlighten me on that one :P