PHP pack html output into a variable - php

Is it possible in PHP to grab the output of HTML code into a variable? Basically, I'm searching for a shorthand for this code:
<?php ob_start(); ?>
<div class="headSection">
<h1><?=$headline?></h1>
<p><?=$bottomline?></p>
</div>
<?php $contents = ob_get_contents(); ob_end_clean(); ?>
I want the HTML code to be saved in the $contents variable.

use PHP's EOF string
$str = <<<EOF
<div class="headSection">
<h1>$headline</h1>
<p>$bottomline</p>
</div>
EOF;
echo $str;
Demo http://codepad.org/9OeUiJNJ

Related

How to echo inside html tags

Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<php? echo $text; ?>
Why is this not printing out link and text assigned in the php code inside the html tags?
If you'll always be running your code in PHP 5.4+, you could use short echo tags;
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<?= $text ?>
Looks a little neater in my opinion, but it's a matter of preference, and short echo tags aren't on by default in earlier versions of PHP, so I wouldn't recommend it if your code is ever going to run on server with PHP versions below 5.4
Another way
Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
echo ''.$text.'';
?>
Use sprint
<?php
$text ='Click here';
$link = 'http://www.google.com';
echo sprintf(" %s", $link, $text);
?>
Use this
Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<?php echo $text; ?>
It is <?php not <php?
use the below code
<?php echo $text; ?>
For the server to interpret your php you need to close all your php code inside the <?php ?> tags and then echo that variable
Open PHP tags properly
You can embedd PHP inside tag as like :
<?php echo $text;?>

PHP - Find and replace enclosed text in an external HTML file

I have a PHP file that renders an HTML file, inside this HTML file I have this piece of code
<div class="app">{: echo $this->content :}</div>
And I want to replace the opening {: and closing :} tags with the traditional <?php ?> tags to make it look something like this:
<div class="app"><?php echo $this->content ?></div>
$contents = file_get_contents ("file.php");
$contents = str_replace(array('{:', ':}'), array('<?php', '?>'), $contents);
file_put_contents("file.php", $contents);
You could do a simple string replace if you are doing this within PHP
str_replace(array('{:', ':}'), array('<?php', '?>'), $file_content)
Try this :
$string = '<div class="app">{: echo $this->content :}</div>';
$string = str_replace('{:','<?php',$string);
$string = str_replace(':}','?>',$string);
If you want to catch the content inside the you can use this :
$string = '<div class="app">{: echo $this->content :}</div>';
preg_match('/<div class="app">(.+)<\/div>/',$string,$preg_array);
$string = str_replace('{:','<?php',$preg_array[1]);
$string = str_replace(':}','?>',$string);
Output :
<?php echo $this->content ?>

How do I populate a variable using a function?

I have the code below on a page basically what I'm trying to do is fill $content variable using the function pagecontent. Anything inside pagecontent function should be added to the $content variable and then my theme system will take that $content and put it in theme. From the answers below it seems you guys think I want the html and php inside the actual function I don't.
This function below is for pagecontent and is what I'm currently trying to use to populate $content.
function pagecontent()
{
return $pagecontent;
}
<?php
//starts the pagecontent and anything inside should be inside the variable is what I want
$content = pagecontent() {
?>
I want anything is this area whether it be PHP or HTML added to $content using pagecontent() function above.
<?php
}///this ends pagecontent
echo functional($content, 'Home');
?>
I think you're looking for output buffering.
<?
// Start output buffering
ob_start();
?> Do all your text here
<? echo 'Or even PHP output ?>
And some more, including <b>HTML</b>
<?
// Get the buffered content into your variable
$content = ob_get_contents();
// Clear the buffer.
ob_get_clean();
// Feed $content to whatever template engine.
echo functional($content, 'Home');
As you are obviously a beginner here's a much simplified, working version to get you started.
function pageContent()
{
$html = '<h1>Added from pageContent function</h1>';
$html .= '<p>Funky eh?</p>';
return $html;
}
$content = pageContent();
echo $content;
The rest of the code you post is superfluous to your problem. Get the bare minimum working first then move on from there.
Way 1:
function page_content(){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
$content .= page_content();
Way 2:
function page_content( & $content ){
ob_start(); ?>
<h1>Hello World!</h1>
<?php
$buffer = ob_get_contents();
ob_end_clean();
$content .= $buffer;
}
$content = '';
page_content( $content );
Way 3:
function echo_page_content( $name = 'John Doe' ){
return <<<END
<h1>Hello $name!</h1>
END;
}
echo_page_content( );

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');

How do I capture PHP output into a variable?

I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.
The code is sorta like the following in structure:
<?php
$lots of = "php";
?>
<xml>
<morexml>
<?php
while(){
?>
<somegeneratedxml>
<?php } ?>
<lastofthexml>
<?php ?>
<html>
<pre>
The XML for the user to preview
</pre>
<form>
<input id="xml" value="theXMLagain" />
</form>
</html>
My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value).
My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?
<?php ob_start(); ?>
<xml/>
<?php $xml = ob_get_clean(); ?>
<input value="<?php echo $xml ?>" />͏͏͏͏͏͏
Put this at your start:
ob_start();
And to get the buffer back:
$value = ob_get_contents();
ob_end_clean();
See http://us2.php.net/manual/en/ref.outcontrol.php and the individual functions for more information.
It sounds like you want PHP Output Buffering
ob_start();
// make your XML file
$out1 = ob_get_contents();
//$out1 now contains your XML
Note that output buffering stops the output from being sent, until you "flush" it. See the Documentation for more info.
When using frequently, a little helper could be helpful:
class Helper
{
/**
* Capture output of a function with arguments and return it as a string.
*/
public static function captureOutput(callable $callback, ...$args): string
{
ob_start();
$callback(...$args);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}
You could try this:
<?php
$string = <<<XMLDoc
<?xml version='1.0'?>
<doc>
<title>XML Document</title>
<lotsofxml/>
<fruits>
XMLDoc;
$fruits = array('apple', 'banana', 'orange');
foreach($fruits as $fruit) {
$string .= "\n <fruit>".$fruit."</fruit>";
}
$string .= "\n </fruits>
</doc>";
?>
<html>
<!-- Show XML as HTML with entities; saves having to view source -->
<pre><?=str_replace("<", "<", str_replace(">", ">", $string))?></pre>
<textarea rows="8" cols="50"><?=$string?></textarea>
</html>

Categories