Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to return HTML in a PHP function? (without building the return value as a string)

I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:

<?php function TestBlockHTML ($replStr) { ?>     <html>     <body><h1> <?php echo ($replStr) ?> </h1>     </html> <?php } ?> 

I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?

like image 704
seanyboy Avatar asked Feb 09 '09 14:02

seanyboy


People also ask

Can you put HTML in a PHP function?

While HTML and PHP are two separate programming languages, you might want to use both of them on the same page to take advantage of what they both offer. With one or both of these methods, you can easily embed HTML code in your PHP pages to format them better and make them more user-friendly.

How is it possible to return a value from a function in PHP?

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4).

What is the difference between return and echo in PHP?

Echo is for display, while return is used to store a value, which may or may not be used for display or other use.

Where do I write PHP code in HTML?

Using these simple steps, we can easily add the PHP code. Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in which we want to use the PHP. Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of PHP.


1 Answers

You can use a heredoc, which supports variable interpolation, making it look fairly neat:

function TestBlockHTML ($replStr) { return <<<HTML     <html>     <body><h1>{$replStr}</h1>     </body>     </html> HTML; } 

Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.

like image 87
Paul Dixon Avatar answered Sep 21 '22 23:09

Paul Dixon