Converting a response to string in PHP - php

Is there anyway to convert an html response to string in php. let me expalin through an example.
<?php
function printTitle($title="Welcome"){
?>
<div class='mainTitle'>
<div class='titleLogo'>
</div>
<div class='titleString'>
<?php echo $title; ?>
</div>
</div>
<?php
}
?>
Here calling this function anywhere will output html showing title.
Now what I need is to convert this response into string value so that it can be passed as json response like:
$response=array("title"=>printTitle(),"sidebar"=>getSideBar());
echo json_encode($response);
I want to do it like this so that I can fetch title and sidebar via ajax.
One way to do it is like:
<?php
function printTitle($title="Welcome"){
$ret="<div class='mainTitle'>
<div class='titleLogo'>
</div>
<div class='titleString'>
". $title ."
</div>
</div>";
return $ret;
}
?>
but this makes html really a mess.

You can use a HEREDOC:
function printTitle($title="Welcome"){
return <<<HTML
<div class='mainTitle'>
<div class='titleLogo'>
</div>
<div class='titleString'>
$title
</div>
</div>
HTML;
}

Use output buffer:
function printTitle($title="Welcome"){
ob_start();
...
return ob_get_clean();
}
Changed from ob_get_flush() to ob_get_clean();

Related

Unable to return output of PHP function, while echo displays string

I am using a PHP function to output a string of HTML. I was initially just echoing the output, but my HTML was displaying too high on the page when I did that. In the past, using ob_start() and returning ob_get_clean() has solved this issue, yet it is not working in this case. In fact, when I use this method, no HTML is output at all. When I use var_dump() on the variable, it is confirming that my HTML string is indeed being saved into the object, yet return still outputs nothing.
<?php
add_shortcode( 'slider-display', 'slider_display' );
function slider_display(){
$slider_html = '';
ob_start();
?>
<!-- Slider main container -->
<div class="swiper-container one-column-swiper" id="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class='slide-content'>
<img src="img.jpg">
</div>
</div>
<div class="swiper-slide">
<div class='slide-content'>
<img src="img.jpg">
</div>
</div>
</div>
</div>
<?php
$slider_html = ob_get_clean();
return $slider_html;
} //end function
Any help is very much appreciated!

How to load page template and put content into?

Maybe it's duplicate but I don't know how it calls and cannot find. I need to load a php-file (template of my block) and set content into it.
For example, template file:
<?php include_once 'boot.inc' ?>
<div class="widget">
<div class="widget-title">I need to put title here</div>
<div class="widget-body">I need to put content here</div>
</div>
And php function to insert new block with this template:
function nm_new_block($title, $content) {};
Can I do it in php?
1° Solution: You need to change you code into:
<?php include_once 'boot.inc' ?>
<?php include_once 'template.php' ?>
<div class="widget">
<div class="widget-title"><?php echo $title; ?></div>
<div class="widget-body"><?php echo $content; ?></div>
</div>
In template.php file you must have something like this:
<?php
$title="My Title";
$content="My Content";
?>
And you don't need function for this cause variables are stored in template.php
2° Solution: You need to implement a function to retrieve variables from external source:
<?php include_once 'boot.inc' ?>
<?php include 'functions.php' ?>
<div class="widget">
<div class="widget-title"><?php echoTitle(); ?></div>
<div class="widget-body"><?php echoContent(); ?></div>
</div>
In functions.php
<?php
function echoTitle(){
$title = 'Add code to get title here';
echo $title;
}
function echoContent(){
$content = 'Add code to get content here';
echo $content;
}
Replace Add code to get title here and Add code to get content here with code to get contents ex:
$title = $_POST['title']; supposing you want get title by a submission form
I do not have enough details to tell you more.

How to output html from php script that also contains '<?php ?>'?

I have the following code in php and I am failing to output what is contained in the 'include_once('aux_files/requestAuthParticip_aux.php')' line. I suspect I have not got the syntax correct but do not know how to fix this. please can someone advise?
<?php
$requestMemBox = '
<div id="topAuth">
<div id="authorHeading" data-pubid='.$pubID.'>Authors Taking Questions</div>
<div id="inviteAuthor">
<input id="searchAutorInvite" type="text" placeholder="Invite Author">
<div id="wrapSuggestAuthor"></div>
</div>
</div>
<div id="wraplistOfAuthors">
<?php include_once('aux_files/requestAuthParticip_aux.php'); ?>
</div>
';
?>
You can use ob_get_contents();
<?php
ob_start();
include('aux_files/requestAuthParticip_aux.php');
$output .= ob_get_contents();
ob_end_clean();
?>
<?php
$requestMemBox = '
<div id="topAuth">
<div id="authorHeading" data-pubid='.$pubID.'>Authors Taking Questions</div>
<div id="inviteAuthor">
<input id="searchAutorInvite" type="text" placeholder="Invite Author">
<div id="wrapSuggestAuthor"></div>
</div>
</div>
<div id="wraplistOfAuthors">
'. $output .'
</div>';
?>
You're trying to assign an include to a variable, which isn't going to work, but you're also doing it in the middle of a string, which is definitely not going to work.
To achieve what you want, you should exit PHP mode, pull in the file's contents to append to your string, then re-enter PHP mode to continue processing as much as you want.
If the thing you're importing contains text you want inside your variable (which is how you're trying to use it right now), then something like this is probably what you want:
<?php
$requestMemBox = '
<div id="topAuth">
<div id="authorHeading" data-pubid='.$pubID.'>Authors Taking Questions</div>
<div id="inviteAuthor">
<input id="searchAutorInvite" type="text" placeholder="Invite Author">
<div id="wrapSuggestAuthor"></div>
</div>
</div>
<div id="wraplistOfAuthors">';
$requestMemBox .= file_get_contents('aux_files/requestAuthParticip_aux.php');
$requestMemBox .= '</div>';
?>
If your included script includes some actual functionality, then you really ought to include it up front and grab its value using a function call, and append that to your string.
replace this line
<?php include_once('aux_files/requestAuthParticip_aux.php'); ?>
with
';
ob_start();
include_once('aux_files/requestAuthParticip_aux.php');
$requestMemBox .= ob_get_clean();
$requestMemBox .= '</div>';
Is one way!
look up ob_start(); to see whats going on here.

$_POST is not working while sending Chtml data from view to controller. Its showing an empty array

I am new in Yii framework. I am using Chtml form to send data from view to controller and want to print the result and insert it to database. But in my case its showing an empty array. I couldn't able to understand where I am doing wrong. So please help me regarding this.
in controller
public function actionTest1()
{
$obj = new Pad;
if(isset($_POST))
print_r($_POST);// to check the desired result
if(isset($_POST['Pad']))
{
$obj->attributes=$_POST['Pad'];
if($obj->save()) // insert the data
$this->redirect(array('view','id'=>$obj->id));
}
}
in view
<?php echo CHtml::beginForm('','post',array('id'=>'step1Form')); ?>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'Stop Pad after goal is reached'));
?>
</div>
<div class="currencyText padTop4 floatLeft">Stop Pad after goal is reached</div>
<div class="clearBoth"></div>
</div>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'No limites'));
?>
</div>
<div class="currencyText padTop4 floatLeft">No limites</div>
<div class="clearBoth"></div>
</div>
<div class="nextText">
<?php echo CHtml::link('Next >',array('pad/test1'));?>
</div>
<?php echo CHtml::endForm(); ?>
Please help. Thanks in advance!
You are not submitting your form and of course $_POST will be empty. Line below is just a link:
<?php echo CHtml::link('Next >',array('pad/test1'));?>
You must change it to :
<?php echo CHtml::submitButton('Next >');?>
And also add an action to your form.
Updating the question with the changes I have done. Its redirect me to pad/test1 showing array() as result.
in controller
public function actionTest1()
{
$obj = new Pad;
if(isset($_POST))
CVarDumper::dump($_POST);// to check the desired result
if(isset($_POST['Pad']))
{
$obj->attributes=$_POST['Pad'];
if($obj->save()) // insert the data
echo "=====";
}
}
in view
<?php echo CHtml::beginForm( '','post'); ?>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'Stop Pad after goal is reached'));
?>
</div>
<div class="currencyText padTop4 floatLeft">Stop Pad after goal is reached</div>
<div class="clearBoth"></div>
</div>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'No limites'));
?>
</div>
<div class="currencyText padTop4 floatLeft">No limites</div>
<div class="clearBoth"></div>
</div>
<div class="nextText">
<?php echo CHtml::button('Next >', array('submit' => array('pad/test1'))); ?>
</div>
<?php echo CHtml::endForm(); ?>
A common source of confusion among new Yii users is how the 'safe' validator works, how it works with other validators, and why it's necessary in the first place. This article means to clear up this confusion, as well as explain the notion of Massive Assignment.
http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/

Add HTML elements to the current page using PHP

So I have the need to dynamically add html content using php which isnt the tricky part but I'm trying to put the HTML into a different location in the document than where the PHP is being run. So for example:
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
echo "<div id=\"secondDivA\"></div>";
?>
</div>
<div id="secondDiv">
</div>
But I want to be able to place the some HTML inside "secondDiv" using the PHP that is executed in the "firstDiv". The end result should be:
<div id="firstDiv">
<div id="firstDivA"></div>
</div>
<div id="secondDiv">
<div id="secondDivA"></div>
</div>
But I have no idea how to go about doing that. I read about some of the DOM stuff in PHP 5 but I couldn't find anything about modifying the current document.
You can open/close "blocks" of PHP wherever you like in your HTML
<div id="firstDiv">
<?php echo '<div id="firstDivA"></div>'; ?>
</div>
<div id="secondDiv">
<?php echo '<div id="secondDivA"></div>'; ?>
</div>
You can also capture the output if necessary with ob_start() and ob_get_clean():
<?php
$separator = "\n";
ob_start();
echo '<div id="firstDivA"></div>' . $separator;
echo '<div id="secondDivA"></div>' . $separator;
$content = ob_get_clean();
$sections = explode($separator, $content);
?>
<div id="firstDiv">
<?php echo $sections[0]; ?>
</div>
<div id="secondDiv">
<?php echo $sections[1]; ?>
</div>
Why not just move the relevant code to the right place?
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
?>
</div>
<div id="secondDiv">
<?php
echo "<div id=\"secondDivA\"></div>";
?>
</div>
The .php file is continuous thus if you have two separate <?php ?> tags they will be able to share the same variables.
<div id="firstDiv">
<?php
echo "<div id=\"firstDivA\"></div>";
$div2 = "<div id=\"secondDivA\"></div>";
?>
</div>
<div id="secondDiv">
<?php echo $div2 ?>
</div>
This will give the desired effect. (Demonstrates the use of variables)
I'm not sure what you're asking. Perhaps just add an echo statement to the second div.
<div id="firstDiv">
<?php echo "<div id=\"firstDivA\"></div>"; ?>
</div>
<div id="secondDiv">
<?php echo "<div id=\"secondDivA\"></div>"; ?>
</div>
Or do you mean you want to make DIV changes after PHP? Try jQuery!
Or do you mean you want to make DIV changes before PHP is finished? Perhaps phpQuery is good for you then.
If you want to work with XML-data (read XHTML), you'd rather use an appropriate XML processor.
DomCrawler is an excellent to work with DOM. It works with the native DOM Extension and therefore is fast and widely used.
Here an example from the doc on how to add content:
$crawler = new Crawler();
$crawler->addHtmlContent('<html><div class="foo"></div></html>');
$crawler->filter('div')->attr('class') // returns foo

Categories