get resulting content of a file without including it - php

01.php
<div class='title'>title</div>
02.php
<?php include('01.php');?>
some function:
$a = file_get_contents('02.php');
echo $a;
Result:
<?php include('01.php');?>
Is there a way to refer 02.php (without including it in the current file) and get this:
<div class='title'>title</div>
This is a simplified example. In reality 02.php is a large file with 01.php included somewhere inside.

If you want to parse the php file and save the result to a variable instead of outputting it you could use:
ob_start();
include("01.php");
$a = ob_get_contents();
ob_end_clean();
You will have the parsed php in $a but it will not be output to the user.
More info: http://php.net/manual/en/ref.outcontrol.php

Related

How to set and output the buffer contents php

I'am really very new to PHP.
I have this code:
<?php cms_loop('500');?>
<div class="item">
<p class="contents"></p>
</div>
<?php cms_loop_end('500');?>
I want to output everything between cms_loop and cms_loop_end functions.
I do it this way:
function cms_loop($id){
ob_start();
echo ob_get_contents();
}
and
function cms_loop_end(){
ob_end_flush();
}
But that's not working. Any help appreciated
Below you can find the working code:
<?php
/**
* Start buffering
* #param $id
*/
function cms_loop($id){
ob_start();
}
/**
* Output everything buffered
*/
function cms_loop_end(){
ob_end_flush();
}
?>
<?php cms_loop('500');?>
<div class="item">
<p class="contents">Hello from buffered content</p>
</div>
<?php cms_loop_end('500');?>
Please note that I removed the echo ob_get_contents(); from your cms_loop() function.
Demo: https://onecompiler.com/php/3wuscawt7
(There is an option to run without account)
I'm assuming you're trying to achieve some kind of template rendering as you apparently trying to render some piece of HTML for later use. For that to happen, PHP needs to be aware of that piece. In your example, though, both PHP and HTML co-exist side by side without either side having any knowledge about the other. Your HTML isn't part of PHP's realm yet.
Let's change that.
The piece of HTML you've given is often called a partial, i.e. something that's meant to be part of something bigger. Like a sidebar being a conceptual part of an index.html file, but not a physical one unless included:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Welcome!</h1>
<!-- Partial -->
<?php include_once('sidebar.html') ?>
</body>
</html>
So let's take a similar approach and factor out the HTML into its own file first:
<div class="item">
<p class="contents"></p>
</div>
partial.html.php
Now we need to find a way to transfer this piece of HTML into the realm of PHP. The simplest approach would be to read it and assign it to a variable:
$html = file_get_contents('partial.html.php');
Let's get back to your function for a second, because now you could do:
function cms_loop($html){
echo $html;
}
I have taken $id off of the list of the function's parameters, mostly because of the following reasons:
you don't read nor write to a database yet
if you did, this would be the wrong place
you don't use any variables in your template, so there's no need to pass any in
Though let's ponder the last one a bit. Wouldn't it be nice if we could pass data into our template, for example to dynamically change the classes we have assigned to both HTML elements?
It would most definitely be nice, and it's possible, too - what we need for that is just a little bit of output buffering. But first, let's change our template to meet our new needs:
<div class="<?php echo $class_outer ?>">
<p class="<?php echo $class_inner ?>"></p>
</div>
So we'll have to define both values up front. But we might end up with a lot more template variables once we get the hang of it, so let's best use an array as a container to store our current and any future values:
$data = [
'class_outer' => 'item',
'class_inner' => 'contents',
];
Next, we'll need some function to render our template with the values we just defined, so it'll need two parameters: The path to the template file and our data array. Also, we want it to return our rendered template. That said, it'll probably look like this:
function render(string $template_path, array $data): string {
if (!is_file($template_path)) {
return false; // Or some better error handling
}
// Let's have some sugar in our templates: Import all indexes
// of our data array as variables into the current scope so
// they can easily be accessed by the template we're about to render.
//
// In other words, we now have two new variables:
//
// - $class_outer (extracted from $data['class_outer'])
// - $class_inner (extracted from $data['class_inner'])
//
// Cf. https://www.php.net/manual/en/function.extract.php
extract($data);
// Start output buffering
ob_start();
// Render template
include $template_path; // By including it, it has access to all
// variables defined in the current scope, i.e.
// inside this very function - like the variables
// we just extracted from $data
$rendered = ob_get_contents(); // Assign all output to a variable, so we can return it.
// End output buffering
ob_end_clean();
return $rendered;
}
Now, we can call that like:
$rendered = render('templates/partial.html.php', $data);

PHP - Reading contents of another PHP file without it echoing

I am trying to reach the contents of a PHP file without the file actually outputting what it would usually do. Here is my test code:
File1 (test1.php)
<?php
ob_start();
include_once './test2.php';
$test = ob_get_contents();
echo $test;
?>
and here is file2 (test2.php)
<?php
$testVar = 'Name!';
?>
<div class="testClass"><?php echo $testVar?></div>
<p>Spam2</p>
and I want it to only do this because of the
echo $test
line NOT because the file is outputting the content.
<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>
due to the echo, but it returns this
<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>
<p>Spam2</p><div class="testClass">Name!</div>
<p>Spam2</p></body>
So how do I get it to only return the content once?
Don't echo $test;. PHP is executing as it should. Since ./test2.php shows Spam in HTML it appears on the page, then you assign the page contents to a variable and echo it. What do you expect?
If you have 2 files say: app/index.php and app/config.php you can just use the return keyword to return some content from the config.php file. And then, when you include the file whatever you returned from config.php can be saved to a variable.
Example:
First return whatever you want from the config.php file (could be an array, string, etc).
<?php
return ['name' => 'Spam'];
Then in the index.php:
<?php
$contents = include_once('config.php');
echo $contents;

Forcing file_get_contents() not to render php codes as plain text

How can I get expected output from example below?
Note: I'm using $content = file_get_contents('content.php'); to use content where and when possible so it is not a direct output on screen. include() breaks the pages.
content.php
<p>Hello <?php echo 'World!'; ?></p>
reader.php
<b>Message from another file:</b> <?php echo file_get_contents('content.php'); ?>
Output of code above is:
Message from another file: Hello <?php echo 'World!'; ?>
Instead of (expected):
Message from another file: Hello World!
I think you are looking for <?php include('content.php');
file_get_contents — Reads entire file into a string
PHP.net file_get_contents - manual
The include statement includes and evaluates the specified file.
PHP.net include - manual
Try making content.php into a file that has a function that returns the content you want (you may want to have parameters). Simply require the file then call the function and save the output.
Example:
content.php
function get_content($world){
return '<p>Hello ' . $world . '</p>';
}
reader.php
<?php
require('content.php');
$content = get_content('world');
?>
<b>Message from another file:</b> <?php echo $content; ?>
Since you cannot use include (though I don't understand fully why), but want the file to be parsed and executed as PHP code, you can use eval
<b>Message from another file:</b> <?php eval(file_get_contents('content.php')); ?>
But the file content.php should not contain <?php and ?> tags, as stated at http://php.net/eval.

Contents of a file_get_content() to process PHP

I am need to use some PHP tags on a file(subfile) that is being called into a template using file_get_contents(Subfile).
I initially used require(subFile) instead of file_get_contents(). But it doesnt quite work as my content gets placed in the wrong spot. And also I can't change the template file to use require().
my template is something like this:
//TEMPLATE FILE.php
$html = file_get_contents(subFile); //I CAN NOT CHANGE THIS FILE
Then my sub file, the one I can change.
//SUB FILE.php
<div>Hello world, today is <?php echo date($mydate);?> </div>
Because it is being called with file_get_contents(), it out puts
Hello world, today is <?php echo date($mydate);?>
Instead of:
Hello world, today is Thursday.
So, considering I can't change my TEMPLATE FILE.php where the file_get_content() is used.
I was thinking if there is a way that I can wrap the content of SUB FILE.php so it would process the PHP before allowing it to be called by the TEMPLATE FILE.php.
Something like this I am after
//SUB FILE.php
<force Process the PHP ?>
<div>Hello world, today is <?php echo date($mydate);?> </div>
<Finishe Force Process ?>
<allow it to be called via file_get_content();
If I could change the template file I could use htmlspecialchars_decode(); but I can't.
Unfortunately I couldn't find a way to do that so I end up with this
ob_start();
$output = include (Dir/SubFile);
$output = ob_get_contents();
ob_end_clean();
$html = $output;
//$html = file_get_contents(subFile); The way it was
The following is an example of the official manual
$homepage = file_get_contents('http://www.example.com');
echo $homepage;
try this:
file_get_contents('http://YourDomain/Yoursubfile');
You cann't use <?php echo $a; ?> to echo the content of variable $a.
Because you will get the plain html content from your subfile.
What you can do is to:-
Step1: my_date.php
<?php
$today = date('M-d-Y');
$subfile_html = file_get_contents(subFile); //Path to my_date1.html or my_date1.php
echo $new_html_content = str_replace('{TODAYS_DATE}', $today, $subfile_html); // It will replace the occurance {TODAYS_DATE} with today's date
// OUTPUT:
// Hello world, today is June 20 2014
?>
Step2: my_date1.html or my_date1.php
<div> Hello world, today is {TODAYS_DATE} </div>

How to get output from local script in PHP?

For example, in foo.php:
<?php echo 'hello'; ?>
And in bar.php, I want to get the output of foo.php (which is hello) and do some formatting before outputting to browser. Is there any way to do this?
Or even further, if the webserver can run both PHP and Python scripts, can a PHP script get the output of a Python script?
Edit:
PHP function file_get_contents() can do this only for remote scripts. If it is used on local scripts, it will return the contents of the whole script. In the example above, it returns rather than hello. And I don't want to use exec()/system() things and CGI.
You can use PHP's output buffers and functions like ob_start(); and ob_get_contents(); to read the contents of your PHP output into a string.
Here is the example on php.net:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
And another:
<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
echo "World";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out1, $out2);
?>

Categories