How do I capture PHP output into a variable? - php

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>

Related

How to convert php code to html source code?

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. :-)

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!

Trying to remove script tags in HTML

I am trying to remove script tags from HTML using PHP but it doesn't work if there's HTML inside the javascript.
For example, if the script tags contain something like this:
function tip(content) {
$('<div id="tip">' + content + '</div>').css
It will stop at </div> and the rest of the script will still be taken into account.
This is what I have been using to remove the script tags:
foreach ($doc->getElementsByTagName('script') as $node)
{
$node->parentNode->removeChild($node);
}
How about some regex-based pre-processing?
Example input.html:
<html>
<head>
<title>My example</title>
</head>
<body>
<h1>Test</h1>
<div id="foo"> </div>
<script type="text/javascript">
document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
</script>
</body>
</html>
Script tag removing php script:
<?php
// unformatted source output:
header("Content-Type: text/plain");
// read the example input file given above into a string:
$input = file_get_contents('input.html');
echo "Before:\r\n";
echo $input;
echo "\r\n\r\n-----------------------\r\n\r\n";
// replace script tags including their contents by ""
$output = preg_replace("~<script[^<>]*>.*</script>~Uis", "", $input);
echo "After:\r\n";
echo $output;
echo "\r\n\r\n-----------------------\r\n\r\n";
?>
You can use strip_tags function. In which you can allow the HTML attributes which you want allowed.
I think this is 'here and now' problem, and you need no something special. Just do something like this:
$text = file_get_content('index.html');
while(mb_strpos($text, '<script') != false) {
$startPosition = mb_strpos($text, '<script');
$endPosition = mb_strpos($text, '</script>');
$text = mb_substr($text, 0, $startPosition).mb_substr($text, $endPosition + 7, mb_strlen($text));
}
echo $text;
Only set encoding for 'mb_' like functions

PHP pack html output into a variable

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

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

Categories