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
Related
I'm trying to add some Javascript coming from Google for Ad Conversions on the thank you page. So this script should only appear on one page. Trying to use an if statement in PHP to echo the code but running into errors. This is what I currently have (with the Google ID replaced with something generic):
<?php if ( is_page( 'thankyou' )) {
echo '<script>';
echo 'gtag('event', 'conversion', {'send_to': 'AW-12345678901234567890123456'});'
echo '</script>';
?>
The first and third echo's are fine but the middle one is not. What might be the proper fix?
Your second echo line breaks your string.
You have 2 options to fix this:
1. Change the inner quotes to double quotes
echo 'gtag("event", "conversion", {"send_to": "AW-12345678901234567890123456"});';
2. Break out of the quotes.
You can use back slashes to not break out of your main string.
echo 'gtag(\'event\', \'conversion\', {\'send_to\': \'AW-12345678901234567890123456\'});';
I have also noticed on the second echo you were missing a semi colon.
Source: PHP-Strings
You need to escape the single quotes in the brackets of gtag().
Try echo 'gtag(\'event\', \'conversion\', {\'send_to\': \'AW-12345678901234567890123456\'});' instead.
I have just started learning PHP, so please forgive me for asking a question like this.
I have a variable $myVar = "hello"; and I want to print out the name of the variable and its value to the browser.
I tried
echo "$myVar: $myVar"; //this simple prints out the value of $myVar twice
also tried
echo '$myVar'+ ":$myVar"; //somehow the number 0 was printed out to the browser
also tried
echo '$myVar: $myVar'; //this just prints out the string literal itself
I understand the difference between double quotes and single quotes, but just can't seem to get this simple example working.
You can simply do this:
echo "\$myVar: $myVar";
Use backslash \ to display the variable name as it is.
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
I'll show the main parts of the code as most of it is irrelevant:
$url = $row['url'];
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($url)'>";
and the javascript function:
function myFunction(something) {
alert (something);
}
I recieve the following error in firebug:
missing ) after argument list
[Break On This Error]
myFunction(http://anything.com/anything...
-------------------^
I am relatively new to javascript but I can tell it is obviously not allowing the ":" from the url. However, I can't change or alter the id, as I need to alert the exact id of the Image.
I have made this work in a different format without the php, so I assume it's there where the problem lies?
The URL needs to be a string, but you're just outputting the string's contents.
You could just put quotes around it as suggested elsewhere, but that's at best an incomplete solution.
Fortunately, PHP gives you a better answer: json_encode combined (in your case) with htmlspecialchars. This is a function that (amongst other things) will properly wrap a string for you such that you can use it in JavaScript code. So:
$escapedUrl = htmlspecialchars(json_encode($url));
then
...onclick='myFunction($escapedUrl)'...
json_encode is for encoding text as JSON, but as JSON is a subset of JavaScript literal notation, and json_encode quite happily returns a valid, properly-escaped JavaScript string...
You need the htmlspecialchars as well because you're then outputting the JavaScript code you're generating into the onclick attribute, and the content of all HTML attributes in HTML text (even ones with code in them) must be properly encoded so (for instance) & must be &, etc.
Do this:
$escapedString = json_encode($url);
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($escapedString)'>";
T.J. Crowder is right, and you can check this out for more information:
What is the correct way to escape text in JSON responses?
Why is my first solution incorrect (even if it seems to work with 1 case)?
Read this: http://kunststube.net/escapism/
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>";
You basically need to print double quotes around the the value passed into the myFunction call:
onclick='myFunction(\"$url\")'
This is because you are doing something like this:
myFunction(http://anything.com)
Function parameter need to be enclosed within quotes or doble quotes in case of string parameters:
myFunction("http://anything.com")
So your echo should look like:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>"
Also you should take into account that $url doesn't have to contain valid characters, so you should add some encoding/escaping (think in terms of XSS).
You have to use the encodeURI(uri) function:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(encodeURI(\'$url\'))'>";
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 :)