Return HTML from PHP function - php

I have a PHP function that I'm using to output a standard block of HTML
<?php function test () { ?>
echo(" <html>
<body><h1> HELLO </h1> </body>
</html>
<?php } ?>
but i see the string of HTML and not the page
I have see this
Is there any way to return HTML in a PHP function? (without building the return value as a string)

if you use SLIM framework change the content type:
$app->contentType('application/json');
to:
$app->contentType('text/html');
then use render function of slim instance with specific template or simply echo html string

you have to do
<?php
function text() {
echo '<html><body><h1>Hello</h1></body></html>';
}
?>
But in addition this is not the base valid structure of a page. You're missing the <head /> tag.

Try this:
<?php
function test ()
{
echo '<html><body><h1> HELLO </h1> </body></html>' ;
}
?>

Try this:
<?php
function text() {
return '<html><body><h1>Hello</h1></body></html>';
}
?>
and where you need it just:
<?php echo text(); ?>

Try out this:
<?php
function test()
{
$html = '<html>';
$html .= '<body>';
$html .= '<h1>Hello</h1>';
$html .= '</body>';
$html .= '</html>';
echo $html;
//or
return $html;
}
?>

In PHP you have something called heredoc which lets you write large amounts of text from within PHP, but without the need to constantly escape things. The syntax is <<<EOT [text here] EOT;
So in your case you can have the function return the text like this
function test() {
return <<<EOT
<html>
<body><h1>HELLO</h1></body>
</html>
EOT;
}
Then just call function test to get the contents
echo test();

Related

PHP is replcing The < & > in a php statement with HTML comments

I am currently trying to create a small template engine for a project that I am working on, and I am using a system where I am replacing {$tag} with a preset tag. So say I put {username} in my template file, it will return a string which is the username. Now I want to go beyond just a simple string replacing a string. So using the same code I put
$tpl->replace('getID', '<?php echo "test"; ?>);
And it didn't work, so when I went to inspect element, I saw that it returned <!--? echo "test"; ?-->...
So now I am just trying to figure out why it returned commented code.
Here is my class file:
class template {
private $tags = [];
private $template;
public function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
public function __construct($templateFile) {
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function set($tag, $value) {
$this->tags[$tag] = $value;
}
private function replaceTags() {
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
public function render() {
$this->replaceTags();
print($this->template);
}
}
And My index file is:
require_once 'system/class.template.php';
$tpl = new template('templates/default/main.php');
$tpl->set('username', 'Alexander');
$tpl->set('location', 'Toronto');
$tpl->set('day', 'Today');
$tpl->set('getID', '<?php echo "test"; ?>');
$tpl->render();
And my template file is:
<!DOCTYPE html>
<html>
<head></head>
<body>
{getID}
<div>
<span>User Name: {username}</span>
<span>Location: {location}</span>
<span>Day: {day}</span>
</div>
</body>
</html>
You're redeclaring PHP in a php file when there is no need to. i.e. you're trying to print <?php which is why it's messing up.
So, you can replace this:
$tpl->set('getID', '<?php echo "test"; ?>');
with this
$tpl->set('getID', 'test');
But, you obviously already know that, you're just trying to go further, the way to do this is by using php inside the set. So, as an idea, you could try this:
$tpl->set('getID', testfunction());
(You're calling testfunction here to define the 'getID' here btw)
So, now you want to write a little function to do something fancy, for the sake of this example:
function testfunction(){
$a = 'hello';
$b = 'world';
$c = $a . ' ' . $b;
return $c;
}
The above should then return hello world in place of {getID}
In reference to your comments - if you want to go one step further and start being more advanced with the return results, you can do the following:
function testfunction(){
$content = "";
foreach ($a as $b){
ob_start();
?>
<span><?php echo $b->something; ?></span>
Some link
<div>Some other html</div>
<?php
$content += ob_get_clean();
}
return $content
}

using a php variable inside of html using a jquery insertAfter

I've got a php function that is something like this
function get_some_info()
{
$location = other_function_that_returns_a_string();
return <<<HTML
<script>
$("<h1> <?php echo $location ?> </h1>").insertAfter("header");
</script>
HTML;
}
but I can't get my variable to dynamically display.
I've also tried something like this
$("<h1> <?php $location = other_function_that_returns_a_string() echo $location?> </h1>").insertAfter("header");
and it never displays anything dynamically. How can I get my variable to show up?
The issue is that you use the HEREDOC syntax.
You don't have to use <?php and ?> inside that.
This will work fine:
$("<h1> $location </h1>").insertAfter("header");
Here is the code I tested in PhpFiddle:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
Header
</header>
<?php
function other_function_that_returns_a_string(){
return "A string";
}
function get_some_info(){
$location = other_function_that_returns_a_string(); // Will be "A string"
return <<<HTML
<script>
$("<h1> $location </h1>").insertAfter("header");
</script>
HTML;
}
echo get_some_info();
?>

Is it possible to use php functions inside heredoc?

Is it possible to use functions within the heredoc template without breaking it?
Somethig like this:
<<<HTML
<div> showcaptcha(); </div>
HTML;
Specifically i wanna require another template in this one without using variables.
Or is there another and more simple solution that is not using heredoc?
Thx in advanced.
For example im using class named requires.
class requires {
public function __construct(){
$this->MYSQL();
$this->FUNC();
}
public function MAIN_MENU() {
require_once ('main-menu.tpl');
}
}
Then what i do in index.php
require_once ('requires.php');
$req = new requires();
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
//bla bla
</head>
<nav><ul class="fancynav">
{$req->HEAD_SCRIPTS()}
</ul></nav>
HTML;
main-menu.tpl
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
And in result i have an empty field without php error
<nav><ul class="fancynav">
</ul></nav>
WTF?
Yes, you can use the "encapsed var" trick:
function hello() {
global $result;
$result = 'hi there!';
return 'result';
}
echo <<<EOF
text ${hello()} text
EOF;
Technically, this works, but it's better to avoid hacks like this in production. A temporary variable will be much cleaner.
Since you cannot directly call a function inside HEREDOC, you may put the function name in a variable, and use that variable inside the HEREDOC string:
$showcaptcha= 'showcaptcha';
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
So you can leave the current already coded function:
function showcaptcha()
{
return "Gotta captcha mall";
}
You could also use:
$showcaptcha = function()
{
return "Gotta captcha mall";
}
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
If the function to call is defined at the same level as the echo (else, you'll have a global variable $showcaptcha).
If you have several functions, you can make a loop before the heredoc:
function dawg()
{
return "I'm loyal";
}
function cat()
{
return "I'm cute";
}
function fish()
{
return "I'm small";
}
function elephant()
{
return "I'm big";
}
$functionsToCall = array('elephant', 'fish', 'cat', 'dawg');
foreach ($functionsToCall as $functionToCall)
$$functionToCall = $functionToCall;
echo
<<<HTML
<br/> Dawg: {$dawg()}
<br/> Cat: {$cat()}
<br/> Fish: {$fish()}
<br/> Elephant: {$elephant()}
HTML;
That's way less ugly than using a global variable
No, it is not possible to use function inside heredoc strings.

content displaying out side of html tags for return and echo

I know that echo will echo the content and return will return the contents for further processing. How ever, I have said function:
class Content{
protected $_html = '';
public function display_content(){
$this->_html = 'content';
}
public function __toString(){
return $this->html;
}
}
then some where I have the following:
$content = new Content();
<p><?php $content->disaply_content(); ?></p>
I get:
<p></p>
content
as the source code for the page. doesn't matter if I echo or just return, either way it displays out side the tag.
Ideas?
I'm not sure where the second 'content' is coming from but note that:
<?php $content->display_content();?>
Will not display anything between the <p> tags. You should use:
<?php echo $content->display_content();?>
(I assume the disaply_content() was a typo in the question and not in the code).

Can I return html from a classic asp vbscript asp function? What about PHP?

Can I call a Classic ASP vbscript function and have it return html? I have a function that does some calculations, but I want it to send back the html as well. Will it do that? .
response.write MyFunction()
function myFunction()
return "<b>test</b>"
end function
I get a type mismatch error.
Second question, please, If this were php, can I send back html and do something like echo MyPHPFunction()?
I didn't know if php was different than asp/vbscript on this. It seems you can send just about anything around in php.
Thank you.
In vb script, assign the return value to the function name; something like this:
function myFunction()
myFunction = "<b>test</b>"
end function
ASP:
<%
Function MyFunction()
MyFunction = "<b>test</b>"
End Function
Response.Write MyFunction()
%>
PHP:
<?php
function MyPHPFunction() {
return "<b>test</b>";
}
echo MyPHPFunction();
?>
ASP with a parameter:
<%
Function MyFunction2(inStr)
MyFunction2 = "<b>" & Server.HTMLEncode(inStr) & "</b>"
End Function
Response.Write MyFunction2("foo & bar")
%>
PHP with a parameter:
<?php
function MyPHPFunction2($inStr) {
return "<b>" . htmlentites($inStr). "</b>";
}
echo MyPHPFunction2("foo & bar");
?>
You could have
<?php
function printHelloWorld(){
echo 'hello world';
}
function getHelloWorld(){
return 'hello world';
}
printHelloWorld();
//output: hello world
echo getHelloWorld();
//output: hello world
?>

Categories