Storing an html page into a php variable [duplicate] - php

This question already has answers here:
HTML into PHP Variable (HTML outside PHP code)
(7 answers)
Closed 4 years ago.
Hi i'd like to store a dinamically generated(with php) html code into a variable and be able to send it as a reply to an ajax request.
Let's say i randomly generate a table like:
<?php
$c=count($services);
?>
<table>
<?php
for($i=0; $i<$c; $i++){
echo "<tr>";
echo "<td>".$services_global[$i][service] ."</td>";
echo "<td>".$services_global[$i][amount]."</td>";
echo "<td>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$services_global[$i][service_price].",00</td>";
echo "<td>".$services_global[$i][service_vat].",00%</td>";
echo "</tr>";
}
?>
</table>
I need to store all the generated html code(and the rest) and echo it as a json encoded variable like:
$error='none';
$result = array('teh_html' => $html, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;
I could maybe generate an html file and then read it with:
ob_start();
//all my php generation code and stuff
file_put_contents('./tmp/invoice.html', ob_get_contents());
$html = file_get_contents('./tmp/invoice.html');
But it sounds just wrong and since i don't really need to generate the code but only send it to my main page as a reply to an ajax request it would be a waste of resources.
Any suggestions?

You don't have to store it in a file, you can just use the proper output buffering function
// turn output buffering on
ob_start();
// normal output
echo "<h1>hello world!</h1>";
// store buffer to variable and turn output buffering offer
$html = ob_get_clean();
// recall the buffered content
echo $html; //=> <h1>hello world!</h1>
More about ob_get_clean()

if the data is so much expensive to regenerate then I would suggest you to use memcached.
Otherwise I would go regenerate it every-time or cache it on the frontend.

for($i=0;$i<=5;$i++)
{
ob_start();
$store_var = $store_var.getdata($i); // put here your recursive function name
ob_get_clean();
}
function getdata($i)
{
?>
<h1>
<?php
echo $i;
?>
</h1>
<?php
ob_get_contents();
}

Related

How to check if text is present on a webpage?

how to check if text is present on a webpage using php and if true to execute some code?
My idea is to show some relevant products on the confirmation page after completing an order - if the name of the product is present on the page, then load some products. But I can't make the check for present text.
Case 1 if you prepare your page in a variable then echo it at the end of the script like
$response = "<html><body>";
$response .= "<div>contents text_to_find</div>";
$response .= "</body></html>";
echo $response;
then you can merely search the string with any string search function
if(strpos($response,"text_to_find") !==false){
//the page has the text , do what you want
}
Case 2 if you don't prepare the page in a string . and you just echo the contents and output the contents outside the <?php ?> tags like
<?php
//php stuff
?>
<HTML>
<body>
<?php
echo "<div>contents text_to_find</div>"
?>
</body>
</HTML>
Then you have no way to catch the text you want unless you use output buffering
Case 3 if you use output buffering - which I suggest - like
<?php
ob_start();
//php stuff
?>
<HTML>
<body>
<?php
echo "<div>contents text_to_find</div>"
?>
</body>
</HTML>
then you can search the output anytime you want
$response = ob_get_contents()
if(strpos($response,"text_to_find") !==false){
//the page has the text , do what you want
}
You may need to buffer your Output like so...
<?php
ob_start();
// ALL YOUR CODE HERE...
$output = ob_get_clean();
// CHECK FOR THE TEXT WITHIN THE $output.
if(stristr($output, $text)){
// LOGIC TO SHOW PRODUCTS WITH $text IN IT...
}
// FINAL RENDER:
echo $output;
Fastest solution is using php DOM parser:
$html = file_get_contents('http://domain.com/etc-etc-etc');
$dom = new DOMDocument;
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
$txt = '';
foreach ($divs as $div) {
$txt .= $div->textContent;
}
This way, variable $txt would hold the text content of a given webpage, as long as it is enclosed around div tags, as usually. Good luck!

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

How to prepend something to the beginning of the PHP output buffer?

How do you append something to the beginning of the output buffer?
For example, say you have the following code:
ob_start();
echo '<p>Start of page.</p>';
echo '<p>Middle of page.</p>';
echo '<p>End of page</p>';
Before flushing the contents to the browser, how can I append something so that it appears before <p>Start of page.</p> when the page loads?
It sounds simple enough, like moving the pointer to the beginning of an array, but I couldn't find how to do it with the output buffer.
** PHP 5.3 **
ob_start(function($output) {
$output = '<p>Prepended</p>'.$output;
return $output;
});
echo '<p>Start of page.</p>';
echo '<p>Middle of page.</p>';
echo '<p>End of page</p>';
** PHP < 5.3 **
function prependOutput($output) {
$output = '<p>Appended</p>'.$output;
return $output;
}
ob_start('prependOutput');
echo '<p>Start of page.</p>';
echo '<p>Middle of page.</p>';
echo '<p>End of page</p>';
Use 2 ob_start commands and ob_end_flush() after what you want to first display then end the buffer with ob_end_flush again when you want to output the rest of the page.
eg:
ob_start();
ob_start();
echo '<p>Start of page.</p>';
ob_end_flush();
echo '<p>Middle of page.</p>';
echo '<p>End of page</p>';
ob_end_flush();
You can get content of buffer using ob_get_contents() function
ob_start();
echo "World! ";
$out1 = ob_get_contents();
echo "Hello, ".$out1;
Are you wanting it before any output at all? If so, then you're looking for the auto_prepend_file directive. http://php.net/manual/en/ini.core.php
See the first parameter of ob_start (documentation here), it allows you to provide a callback to be called when the buffer is flushed or cleaned. It receives a string as a parameter and outputs a string, therefore it should be easy to
function writeCallback($buffer)
{
return "Added before " . $buffer;
}
ob_start("writeCallback");

getting data from php variable

$content = file_get_contents('file.php');
echo $content;
nothing displays, expect when displaying the page sourcecode in browser the display is this
<? foreach(glob("folder/*.php") as $class_filename) { require_once($class_filename); } ?>
so it wont execute the script when getting the content..
file.php contains this code
<? foreach(glob("folder/*.php") as $class_filename) {
require_once($class_filename);
}
?>
and if I do next
$content = foreach(glob("folder/*.php") as $class_filename) { require_once($class_filename); } ?>
it complains about unexpected foreach...
is there a way to read the folder/.php files content to single $variable and then echo/print all folder/.php files to page where it should be?
thanks for help already.
Is that what you want to do ?
$content = '';
foreach (glob('folder/*.php') as $class){$content .= file_get_contents($class);}
echo $content;
What you're trying won't execute the contents of the "file.php", jsut display the contents of them on screen.
If you want to execute file.php, use eval ($content)
To capture the output, use something like:
ob_start(); // Don't echo anything but buffer it up
$codeToRun=file_get_contents('file.php'); // Get the contents of file.php
eval ($codeToRun); // Run the contents of file.php
$content=ob_get_flush(); // Dump anything that should have been echoed to a variable and stop buffering
echo $content; //echo the stuff that should have been echoed above

How do I catch the HTML generated by a function?

I have a php function that generates HTML code like below
function j_uf_SomeFunction($some_var) {
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
}
Of course, its much more advanced and add all sorts of user options.
In most case I place this function inline, as opposed to have to append it to a string. However, I've come to the first occurrence (probably not the last occurrence) where I need to store the rendered HTML in a string and not have it sent straight off to the parser for building the page.
I need to cut the function off and tell it to take the html generated and store it in a string, and not send it off to the page, only on certain situations.
function j_uf_SomeFunction($some_var) {
ob_start();
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
return ob_get_clean();//suggestion by GWW
}
ob_start() is starting buffer receive
ob_get_clean() cleans current buffer and returns its value.
More info on http://php.net/manual/en/function.ob-start.php
ob * output buffering
It sounds like output buffers are one possible solution to your problem.
You use an output buffer like so:
ob_start();
j_uf_SomeFunction($someVar);
$buffer = ob_get_contents();
ob_end_clean();
The $buffer variable now contains anything printed out by the function.
It's important to always close output buffers with ob_end_clean or ob_end_flush. You can read more here: http://php.net/manual/en/book.outcontrol.php
Regards,
Chris
I don't I have a template system to parse this functions value into... its not your standard function call.
sure you do... its jsut contained within the function :-)
using translation:
function j_uf_SomeFunction($some_var) {
$html = "<div class="db_photo"><img alt="%some_function_result%" src="%some_var%" /></div>";
$tokens = array(
'%some_var%' => $some_var,
'%some_function_call_result%' => some_function_call()
);
return strtr($html, $tokens); // or echo
}
using string manipulation:
function j_uf_SomeFunction($some_var) {
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, some_function_call(), $some_var); //or echo
}
if some_function_call actually outputs html directly with its own echo then jsut use a buffer:
function j_uf_SomeFunction($some_var) {
ob_start();
some_function_call();
$somefunc = ob_get_clean();
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, $somefunc, $some_var); //or echo
}

Categories