I am using ob_get_contents() to create a html file from php file. On development machine sometimes it works but on the test machine it did not work.
<html>
<body>
<div>
//some html content
</div>
</body>
</html>
<?php
ob_start();
file_put_contents('./pdfreportresult.html', ob_get_contents());
require_once (APP_DIR . 'assessment/wkhtmltopdf/snappy-master/src/autoload.php');
use Knp\Snappy\Pdf;
$snappy = new Pdf(APP_DIR . 'assessment/wkhtmltopdf/wkhtmltopdf.exe');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
echo $snappy->getOutput(APP_DIR . 'assessment/pdfreportresult.html');
ob_end_clean();
?>
I checked test machine's php.ini for output_buffering and it is "On" like on development machine. When i checked my created html file "pdfreportresult.html" it is empty or half-content is exist.
Maybe issue can related with buffer size and i tried ob_clean() instead of ob_end_clean() still not working.
Start the buffer before you start outputting content. Also, clean the buffer once you're done with it.
<?php
ob_start();
?>
<html>
<body>
<div>
//some html content
</div>
</body>
</html>
<?php
file_put_contents('./pdfreportresult.html', ob_get_contents());
ob_end_clean();
...
Related
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.
I need to display html source code form other php file.
I have two file
code.php
index.php (I hope I can convert the code.php to html source code.)
code.php:
<!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>
index.php (I hope I can convert the code.php to html source code.)
$php_to_html = file_get_contents("code.php");
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;
but when i run the index.php file, the result is
<!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>
but I hope I can see the result is
<!DOCTYPE html> <html> <body> red </body> </html>
any idea how can i do this ,thanks!!!
You want to execute the PHP, so include it and capture the output:
ob_start();
include("code.php");
$php_to_html = ob_get_clean();
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;
If you want the HTML to be rendered as HTML then don't use htmlentities().
Optionally (not the best way) but you can execute it by retrieving from the URL:
$php_to_html = file_get_contents("http://www.example.com/code.php");
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;
Buffer output and include it:
ob_start();
include_once('code.php');
$html = ob_get_clean();
By using output buffering, any output is not sent to the browser, but instead kept in memory. This allows you to run the code, and get the output as a variable. ob_get_clean() flushes the buffer (in this case into our $html variable), and then stops buffering, allowing you to continue as normal. :-)
I'm trying to display the content of a php file to a div.
<div contenteditable="true" id="highlight">
<?php
echo file_get_contents( "/path/test.php" );
?>
</div>
test.php
<?php
require_once (lib.php');
/*
some comments here
*/
session_cache_limiter('private, must-revalidate');
header('Pragma: public');
#ob_start();
#session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
// INCLUDES
define('FPDF_FONTPATH', "path/font/");
// print_r($_GET);
?>
.......................
But the content in the div is displaying from this line only : // print_r($_GET);. I need to display the entire content of the file.
Can anyone help me to fix this? Thanks in advance.
Because the HTML parser of your browser sees <?php as an HTML element it will be commented out. You have to convert < and > to their equivalent HTML entities.
You can do this using htmlspecialchars (using <pre></pre> to keep the new lines from the actual file):
<div contenteditable="true" id="highlight">
<pre><?php // this should be directly after pre to prevent white-space from appearing before the code from the file
echo htmlspecialchars(file_get_contents( "43677696_test.php" ));
?>
</pre>
</div>
You can see the output here.
<?php
include ('mpdf/mpdf.php');
$mpdf = new mpdf;
ob_start();
?>
<html>
<head></head>
<body>
My various content with table, dropdown menu and 2 include files.
</body>
</html>
<?php
$html = ob_get_contents();
ob_end_clean();
$mpdf->Output();
exit;
?>
Wondering why this function doesn't work and will only output empty pdf file. I have tried many ways but it just doesn't work. I have placed this function at the beginning of my code but it always outputs an empty file.
Try this code:-
<?php
$html = ob_get_contents();
ob_end_clean();
// You need to write html
$mpdf->WriteHTML($html);
// define path of your output file and set mode 'F' for saving
$mpdf->Output('filename.pdf','F');
exit;
?>
I am using ob_start()/ob_flush() to, hopefully, give me some progress during a long import operation.
Here is a simple outline of what I'm doing:
<?php
ob_start ();
echo "Connecting to download Inventory file.<br>";
$conn = ftp_connect($ftp_site) or die("Could not connect");
echo "Logging into site download Inventory file.<br>";
ftp_login($conn,$ftp_username,$ftp_password) or die("Bad login credentials for ". $ftp_site);
echo "Changing directory on download Inventory file.<br>";
ftp_chdir($conn,"INV") or die("could not change directory to INV");
// connection, local, remote, type, resume
$localname = "INV"."_".date("m")."_".date('d').".csv";
echo "Downloading Inventory file to:".$localname."<br>";
ob_flush();
flush();
sleep(5);
if (ftp_get($conn,$localname,"INV.csv",FTP_ASCII))
{
echo "New Inventory File Downloaded<br>";
$datapath = $localname;
ftp_close($conn);
} else {
ftp_close($conn);
die("There was a problem downloading the Inventory file.");
}
ob_flush();
flush();
sleep(5);
$csvfile = fopen($datapath, "r"); // open csv file
$x = 1;
// skip the header line
$line = fgetcsv($csvfile);
$y = (feof($csvfile) ? 2 : 5);
while ((!$debug) ? (!feof($csvfile)) : $x <= $y) {
$x++;
$line = fgetcsv($csvfile);
// do a lot of import stuff here with $line
ob_flush();
flush();
sleep(1);
}
fclose($csvfile); // important: close the file
ob_end_clean();
However, nothing is being output to the screen at all.
I know the data file is getting downloaded because I watch the directory where it is being placed.
I also know that the import is happening, meaning that it is in the while loop, because I can monitor the DB and records are being inserted.
Any ideas as to why I am not getting output to the screen?
You also need to check the PHP settings
some installs default to 4096, some default to off
output_buffering = Off
output_buffering = 4096
agreed with George but do check the above settings
Make sure that your output buffering doesn't start automatically. Run:
print ob_get_level ();
before ob_start (); if will will see something else then 0 you've got the answer.
Hey man I was also got stuck in this problem
and finally got the correct solution
here it is for you
you have to add content type for your page
you can do that by two ways
1. using html tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Ex.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wp Migration</title>
</head>
<body>
<?php
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>
</body>
</html>
using php header function
<?php header( 'Content-type: text/html; charset=utf-8' ); ?>
Ex.
<?php
header( 'Content-type: text/html; charset=utf-8' );
for($i=0;$i<70;$i++)
{
echo 'printing...<br>';
ob_flush();
flush();
sleep(3);
}
?>
All the best
Ob_end_clean() discards the contents of the current output buffer and turns off the buffering.
You should use ob_end_flush() instead.
Add this line
header("X-Accel-Buffering: no");
worked for me.
You can edit it with the .htaccess file
To disable output buffering, modify the line as follows:
php_value output_buffering Off
php_value output_buffering 4096
worked for me. Thank you!
Check this site: Click Here
It's possible that your webserver is doing its own buffering. Probably with something like mod_gzip.
Here is some very simple test code:
<?php
echo 'starting...<br/>';
for($i = 0; $i < 5; $i++) {
print "$i<br/>";
flush();
sleep(2);
}
print 'DONE!<br/>';
If it takes 10 seconds for that page to load, rather than seeing a new line every 2 seconds, then it means that it is being cached by your webserver. For what you are trying to do, there is no need to use ob_start and ob_flush. Just call flush whenever you want to force the content to the browser. However, like I mentioned, if the webserver is waiting for the content to complete before sending, then that won't do anything for you.
Edit: Another possibility is that you're viewing the page from behind a corporate or ISP proxy/firewall that waits for the whole page before serving it (so that it can scan it to see if it looks like pornography, for example).