Jump to content

Variable inside of HTML


php-n00b

Recommended Posts

What's Up?

 

OK, So I'm using the IF and ELSE function to echo some html code, But I need to be able to echo the contents of a variable inside of some html code.

 

if ($var1=="text")
echo '<body><text>$text</text></body>'
else
echo 'Failed'

But of course instead of echoing the contents of the $text variable, It just echo $text. I'ved tried putting.

if ($var1=="text")
echo '<body><text>'; echo $text; echo '</text></body>'
else
echo 'Failed'

But I got another error, Someone in IRC mentioned the word backslash, However that was the only advice I got.

 

Thanks Bye!

Link to comment
https://forums.phpfreaks.com/topic/198301-variable-inside-of-html/
Share on other sites

Before I start, you are required to end statements with semi-colons in PHP. Also, is <text> really a HTML tag? I prefer not making stuff up.

 

There are a few ways to do that.

 

1. Variable interpolation

2. String concatenation

3. String formatting

 

1. For variable interpolation, like you had in your first example, you can only do that with double quotes. So if you change those single quotes to double quotes, it should work.

 

2. String concatenations are done via the . (dot) operator. Example:

echo '<body>' . $text . '</body>';

 

3. String formatting is done via a few of PHP functions. sprintf and printf comes to mind. Example:

echo sprintf('<body>%s</body>', $text);

 

I usually prefer the last method because it looks cleaner.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.