How do I catch the HTML generated by a function? - php

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
}

Related

php evaluate code before getting file content

I have a file B590.php which is having a lot of html code and some php code (eg logged in username, details of user).
I tried using $html = file_get_content("B590.php");
But then $html will have the content of B90.php as plain text(with php code).
Is there any method where I can get the content of the file after it has been evaluated?
There seems to be many related questions like this one and this one but none seems to have any definite answer.
You can use include() to execute the PHP file and output buffering to capture its output:
ob_start();
include('B590.php');
$content = ob_get_clean();
function get_include_contents($filename){
if(is_file($filename)){
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
$html = get_include_contents("/playbooks/html_pdf/B580.php");
This answer was originally posted on Stackoverflow
If you use include or require the file contents will behave as though the current executing file contained the code of that B590.php file, too. If what you want is the "result" (ie output) of that file, you could do this:
ob_start();
include('B590.php');
$html = ob_get_clean();
Example:
B590.php
<div><?php echo 'Foobar'; ?></div>
current.php
$stuff = 'do stuff here';
echo $stuff;
include('B590.php');
will output:
do stuff here
<div>Foobar</div>
Whereas, if current.php looks like this:
$stuff = 'do stuff here';
echo $stuff;
ob_start();
include('B590.php');
$html = ob_get_clean();
echo 'Some more';
echo $html;
The output will be:
do stuff here
Some more
<div>Foobar</div>
To store evaluated result into some variable, try this:
ob_start();
include("B590.php");
$html = ob_get_clean();
$filename = 'B590.php';
$content = '';
if (php_check_syntax($filename)) {
ob_start();
include($filename);
$content = ob_get_clean();
ob_end_clean();
}
echo $content;

Using json_encode to send html returns “null” string at the end

I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {
$urlcall = nav_me_paises(); /* fetches a large html string */
$response = json_encode($urlcall); /* encode to display using jQuery */
//header( "Content-Type: application/json" );
echo $response;
exit;
}
I insert the html on the page, using
function(response) {
jQuery('#navcontainer').html(response);
}
and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
?>
<ul class="navcategorias">
<?php $tquery = $_POST['wasClicked']; ?>
<?php $navligas = get_terms($tquery,'hide_empty=0') ?>
<?php foreach ($navligas as $liga) : ?>
<?php $link = get_term_link($liga); ?>
<li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
$output = '<ul class="navcategorias">';
$tquery = $_POST['wasClicked'];
$navligas = get_terms($tquery,'hide_empty=0')
foreach ($navligas as $liga) {
$link = get_term_link($liga);
$output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
}
$output .='</ul>';
return $output;
}
nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};
var_dump(json_encode(foo()));
string(4) "null"
Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?

For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.
snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:
<article>
<h1>{$headline}</h1>
<p>${$body}</p>
</article>
I'd like to be able to return this code from a function, along the lines of this:
function writeArticle($headline, $body){
return "contents of snippet.php using the variables passed in to the function"
}
I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.
One method is using file_get_contents and str_replace
HTML:
<article>
<h1>[-HEADLINE-]</h1>
<p>[-BODY-]</p>
</article>
PHP:
function writeArticle($headline,$body){
$content = file_get_contents("[add your html directory here]/file.html",true);
$content = str_replace("[-HEADLINE-]",$headline,$content);
$content = str_replace("[-BODY-]",$body,$content);
echo $content;
}
You can use output buffering and include the file so the PHP variables get evaluated. However, since you are not using <?php PHP tags ?> you will need to wrap it in HEREDOC format (http://php.net/manual/en/language.types.string.php). Scroll down to Heredoc on the page.
snippet.php
$output = <<<HEREDOC
<article>
<h1>{$headline}</h1>
<p>{$body}</p>
</article>
HEREDOC;
function writeArticle($headline, $body){
ob_start();
include('snippet.php');
$snippet = ob_get_clean();
return $snippet
}
You could do this:
HTML DOCUMENT
Include('blockClass.php');
$block = new blockClass();
echo $bl = $block->block($headline, $body);
CLASS DOCUMENT
class blockClass{
function block($headline, $body){
$var ='<article>
<h1>' . $headline . '</h1>
<p>' . $body . '</p>
</article>';
return $var;
}
}
I had the same question and ended up solving it like this. I feel like this is the cleanest approach. Just turn php on and off within the function.
<?php
function writeArticle($headline, $body){
?>
<article>
<h1><?php echo $headline; ?></h1>
<p><?php echo $body; ?></p>
</article>
<?php
}
?>
writeArticle('foo', 'bar');

Storing an html page into a php variable [duplicate]

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();
}

PHP function return. Cheats allowed

OK.
I have a very long and pretty complicated function.
It looks almost like this one:
<?php
function hello() {
echo 'My Function!' ?>
<ul>
<li> Blablabla </li>
<ul>
(...)
<?php } ?>
The HUGE problem here is that I'm UNABLE to echo anything.
My function HAVE to return it's contents instead of echoing or direct outputting (it has to be that way, it's a Wordpress shortcode and when I echo - the contents are getting displayed at the top of the page - ALWAYS, not in the place where I want them):
<?php
function hello() {
$output .= 'My Function!';
$output .= '<ul>';
$output .='<li> Blablabla </li>';
$output .='<ul>';
(...)
return $output;
} ?>
I hope it's easy till now.
Now, the real problems are:
I have tons of direct input code like:
?>
<div>
<span>
<p>Smth</p>
<a>smth</a>
</span>
</div>
<?php
Adding $output everywhere kills the nice paragraphs/whitespace and code is getting VERY HARD to read and understand (and all HTML elements are parts of variable now, so even my php editor is not treating them well and coloring them as PHP elements).
And another thing, I have tons of lines like this one:
<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link">
(yes, this is a single line)
And I have absolutely no idea how to add such lines to $output.
$output .= '<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link"> ';
Doesn't work of course (even with \'s before ' and ").
I believe there MUST be an easier way to attach all the code to return, but how?
I've tried with ob_start(); before code and return ob_get_clean(); after, but it outputs shortcode name instead of contents.
Its very hard to imagine what the problem you are trying to solve here is - although I'm not familiar with wordpress. Can't you just call the function where the output is supposed to go?
You could use output buffering - use echo/print as usual but...
ob_start();
hello();
$output=ob_get_contents();
ob_end_clean();
But that doesn't solve the problem that you still need to send to the browser at the right place in the page - and if you can do:
print $output;
in the right place, then you can surely do:
hello();
in the same place.
I agree with symcbean, but this might be a more practical approach at integrating with Wordpress: if you now have a single function called hello( ) which displays HTML, you might want to consider renaming that function to hello_content( ) (or something similar) and replace the hello( ) function with the suggestion symcbean gave you:
function hello_content( ) {
echo "foo";
}
function hello( ) {
ob_start( );
hello_content( );
return ob_get_clean( );
}
That should fix your immediate issue.
PHP Heredoc syntax will keep things looking neat and tidy and you can return the output to a variable. As long as you don't require any constants it will work fine.
You use it in this fashion:
function bar() {
$var = <<<EOV
anything here
anything there
EOV;
return $var;
}

Categories