Adding PHP code in HTML which is already in PHP? [duplicate] - php

This question already has answers here:
Simple PHP stuff : variable evaluation [duplicate]
(5 answers)
Closed 11 months ago.
Basically, I want to add a PHP variable in HTML, with that HTML already being inserted into a constant, which is in PHP code. Here's what I mean: (obviously this code below is wrong, but imagine I would want to be inserting the $VARIABLE in the URL of the iFrame, for example)
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/$VARIABLE'></iframe>";
?>
What would be the syntax for adding that variable in there?
Thanks in advance!

This is just a basic template. str_replace() should do the trick.
const EXAMPLE = "<iframe src='http://example.com/{{{VARIABLE}}}'></iframe>";
$variable = 'example-sub-category
$merged_content = str_replace('{{{variable}}}', $variable, EXAMPLE);
Note I used {{{}}} to denote the insert. This is not PHP syntax, but you will find templates often use something like that the would not be expected in the text otherwise to denote placeholders.

Have you tried:
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/".$VARIABLE."'></iframe>";
?>

You can insert PHP anywhere in HTML just by defining its tags <?php ?>
<iframe src='http://example.com/<?php echo $VARIABLE; ?>'></iframe>
Using your example:
const EXAMPLE = "<iframe src='http://example.com/" . $VARIABLE . "'></iframe>";

For this kind of task I'd better use sprintf:
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/%s'></iframe>";
echo sprintf(self::EXAMPLE, $VARIABLE);

To move in and out of php within your html, use <? [php code here...] and ?> to end php and continue with html. You can escape characters with a back slash \ and using single quotes as Rujikin mentioned above. Or, within PHP, you can echo your html so that you're not bouncing in and out of php.
For example:
some php...
echo '<span style=\"color:#980000\"><strong>\"{$searchTerm}\"</strong></span>';
more php...
Notice that the html is enclosed in single quotes (end-to-end) and inside the single quotes, double quotes are used where required by html, e.g., for the <style> tag.
This example is basically saying, "echo whatever the value of php variable $searchTerm is, put it in quotes that's required by echo, and make it dark blue (#0000FF) and bold (<strong>).
I hope this helps. :)

You can try something like:
<?php
$VARIABLE = 'example-sub-category';
const EXAMPLE = "<iframe src='http://example.com/$VARIABLE'></iframe>";
$newHtml = str_replace('$VARIABLE', $VARIABLE);
?>
As you mentioned your code was fake, so I guess what you need is to replace some places in your HTML strings by a content which is unknown until you php script is executed, right ?
so what you need is to put some place holders and change them later, as I showed in my snippet above.
Hope this works

Related

How to prevent PHP variables and expressions from expanding in string

The following text link works fine when I place it directly in my html:
Click here to <?php echo $showOrHideText; ?> the suggested sequence of lessons.
But I want to replace it with:
<?php echo $gradeNote; ?>
Elsewhere $gradeNote is assigned a string based on the grade of the student user. My question after many hours of searching and failing is how can I pass this snippet as a literal string, without PHP attempting to parse it and giving me a junk url? What am I doing wrong here:
$gradeNote = "Click here to <?php echo $showOrHideText; ?> the suggested sequence of lessons.";
You're running <?php and ?> tags inside of a PHP variable. As you're already dealing with PHP, these are unnecessary.
Although the quotation marks "" allow you to echo out evaluated variables, because you're also running a condition in this 'string', you'll want to extrapolate that out and simply store the result as a variable. I've called mine $show.
As such, you're simply looking for:
if($slcustom29 == 0) {
$show = 1;
}
else {
$show = 0;
}
$gradeNote = "Click here to $showOrHideText the suggested sequence of lessons.";
Remember to either escape the double-quotes in the <a href="">, or swap them for single-quotes.
This can be seen working here.
Hope this helps!
Try something like this.
$s = ($slcustom29 == 0) ? 1 : 0;
$gradeNote = "Click here to {$showOrHideText} the suggested sequence of lessons.";
Any string with double quotes "" can have a variable embedded, the {} are not necessary, but i always use them for cases like this where you are trying to embed a variable with no spaces around it, "$xabc" which will return a different result "{$x}ab"
the probelm is that you are trying to put php logic into the string. Notice you have an IF command within the string literal. start with a small or empty string, and concat onto it piece by piece, as opposed to doing it in one line.
then you can echo out the single variable link

PHP: php variable in html link (<a>)

Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

I want to PHP include a variable, doesn't seem to be working

I am trying to PHP include a variable from the database that contains a URL but it doesn't seem to be liking it, any ideas?
The code is
<?php
$location=$row_info['location'];
include '.$location./index.php'; ?>
Thank you for your help :-)
include '.$location./index.php'; ?>
should be
include ".$location./index.php"; ?>
Variable names are not expanded inside single-quotes. From the PHP Manual:
The most important feature of double-quoted strings is the fact that
variable names will be expanded
Try this:
include "$location/index.php"; ?>
Or this:
include $location.'/index.php'; ?>
Either of those should work better. PHP won't actually expand the $variable inside a '' quote, you'll just get $variable as text in the output instead so you want to put the $variable outside the quote using dot between them like the second example or use "" quotes like the first.
you have that a bit backwards...
$location = $row_info['location'].'/index.php';
include $location;
This should work or you could use double-quotes for values and get same results. As stated above. :)~

PHP echo replacement for a variable - ${variable} [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Curly braces in string in PHP
I run into some "strange" PHP code, so instead of this:
<?php echo $variable; ?>
I have this one:
${variable}
and I can't get how to make this to the variable:
<?php echo number_format($variable, 2, ',', '.') ?>
Any ideas?
Thanks.
EDIT: This is the actual code:
<script id="productTemplate" type="text/x-jquery-tmpl">
<?php echo "Save:"; ?> ${savings} <?php echo "or"; ?> ${savings_percentage} <?php echo "%"; ?>
</script>
This one outputs:
Save 15 or 3.2302678810608 %
I need to add number_format to ${savings_percentage} so it can output:
Save 15 or 3.23 %
but have no idea how to...
You're using a jquery plugin (not supported now) called TMPL.
You should convert your data via javascript.
${savings_percentage.toFixed(2)}
You can use native .toFixed method or use some helper (see for example this question)
This is not PHP variable. This is template engine variable or something like part of script written in JavaScript.
Its outside PHP script (defined by <?php ?>).
Read template engine or that script manual for more information.
There is no way to access it from PHP, because this is processed by JavaScript on client machine, after server sends html page to browser. PHP is processed on server and you cant pass variables between browser and PHP code directly.
${variable} syntax
Unless this is inside a double quote string, this is identical to $variable
Double-quoted string
In a double quoted string, you'd use this syntax where, for example, the variable name would otherwise be misinterpreted.
i.e. Here's some code echoing a variable named $variable:
$variable = "something";
echo "This is a string with a $variable";
// outputs "This is a string with a something"
Here's the same code, but in this case the variable is immediately followed by the string "name":
echo "This is a string with a $variablename";
// outputs "This is a string with a "
In addition to the 'wrong' output, it'll throw an undefined variable error because $variablename isn't defined.
Here's the same example, using curly braces to make explicit what is the variable:
$variable_name = "something";
echo "This is a string with a ${variable}name";
// outputs "This is a string with somethingname"
Template engines
From your edit:
<script id="productTemplate" type="text/x-jquery-tmpl">
<?php echo "Save:"; ?> ${savings} <?php echo "or"; ?> ${savings_percentage} <?php echo "%"; ?>
</script>
The variables here are not in php tags, so it's not logical to look for what they mean in a php-context. They are just plain text, and as indicated from the script tag - they are intended to be used with the (defunct) jquery tmpl function.
I need to add number_format to ${savings_percentage} so it can output:
Well, fix the js that you haven't put in the question so that it does that :)

Php echo javascript with variables

have a question about a php echoing script that has a link to a javascript with some variables. I need to know the format for the echo so it will work properly. Could anyone shed any light on this? My code is posted below
echo "<a href='javascript: toggle('variable1', 'variable2')'><label1 for='nameEditor'>Manage</label1></a>";
Now when you hover over the link it just shows javascript:toggle( Now I have tried multiple things and I still cant get it to work. Anyone have any suggestions?
Assuming variable1 and variable2 are the PHP bits you want inserted into the javascript, then
echo "<a href='javascript: toggle('$variable1', '$variable2')'><label1 for='nameEditor'>Manage</label1></a>";
However, be aware that if either of those variables contain Javascript metacharacters, such as a single quote, you'll be breaking the script with a syntax error (think of it as the same situation as SQL injection).
To be sure that the variable's contents become legal Javascript, you'd want to do something like:
<script type="text/javascript">
var variable1 = <?php echo json_encode($variable1); ?>;
var variable2 = <?php echo json_encode($variable2); ?>
</script>
...
try like this:
echo "<label1 for='nameEditor'>Manage</label1>";
you have to escape \ quotes
It's because you're mixing your quotes that the browser see. Do this:
echo "<label1 for='nameEditor'>Manage</label1>";
If you escape the double quotes (\"), you'll be fine. The browser itself is seeing '''' (all single quotes), so you need to retain "''" (double,single,single,double) in your html element attribute, irregardless of PHP (except for the escaping).

Categories