Interpret PHP inside a quote in a PHP - php

I have this variable $url that I need to print inside a quoted HTML that it's inside a PHP if conditional.
<?php
$url = $thumb['0'];
if ( in_category( 'News' )) {
//nothing here
} else {
echo '<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>';
}
?>
But src="$url;" is interpreted as src="$url;" in the HTML code. It does not interpret as a variable.
How can I solve that?

you can concatenate strings with a dot in php
e.g
echo "This"."is"."a"."sample";
likewise with variables:
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';

When working with strings in PHP, it's important to realize the distinction between single- and double-quoted strings.
Single-quoted strings are basically parsed as literal strings, regardless of what 'special' characters you might use. The only escape sequences are \' for a literal single quote and \\ for a literal backslash. PHP code is treated as simple text, and so are escape sequences like \n (the sequence for a unix newline). This is the format to use for simple string literals like 'Hello World!'.
Double-quoted strings are parsed completely, meaning \n is interpreted as a newline and $var is replaced with the value of the variable $var. So this is much more powerful, but you also have to think more about how your strings will be interpreted. If your interpreted php gets complicated (or is adjacent to non-php that might look like php), you can use braces to clarify your meaning.
Note that there are lots of reasons not to mix strings with php code. Often sprintf, heredoc, or simple concatenation (with .) make things much clearer, as suggested in several other answers.

I like to seperate the business logic from the output. This, in combination with PHP's alternative syntax for control structures, keeps your HTML output clean and easily readable.
See this example:
<?php
// Do some things here
$url = $thumb['0'];
// Below this point we output HTML
// Only use simple control structures here, this keeps your HTML clean and easy to read
?>
<?php if (in_category('News')): ?>
<?php else: ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
Since the first part of the if-statement is empty, you can simplify the code:
<?php if (!in_category('News')): ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>

Use double quotes and surround your variable in curley braces example
echo "This is my variable. It equals {$var}";

you can do like this
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';
or
echo "<div class='image-holder'><img src='$url' alt='Post photo' class='image-border'></div>";

If you need to work with large portions of HTML and don't want to have to change from double to single quotes [technically disallowed by HTML spec], or escape all of the double quotes [pain in the butt], or constantly drop in and out of <?php ?> tags [ugly, hard to maintain], then use a HEREDOC. eg:
echo <<<_end_
<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>
_end_;
Variables are expanded, no quotes need escaping, and all of your dreams will come true.
Alternatively, you can stick with a single-quoted string and get cozy with printf() which is a fantastically useful function in its own right. eg:
printf('<div class="image-holder"><img src="%s;" alt="Post photo" class="image-border"></div>', $url);

Do this, (EDIT: simplified code)
<?php
$url = $thumb['0'];
if ( ! in_category( 'News' ) ) {?>
<div class="image-holder">
<img src="<?=$url?>" alt="Post photo" class="image-border" />
</div>
<?}?>

Related

Echoing un-escaped HTML

Very unusual question.
I came across some code some years in the pass that was including conditions and normal PHP syntax while echoing all content.
My question is how is that Technic/syntax called. I have been googling with some very broad terms and can't find what im looking for.
If my memory is correct, The code I viewed long time ago had un-escaped HTML and it was not required to start and stop PHP processing with <?php ?>
I Have a method within a class called Template\Labels::User()
the only purpose of that method is to echo the proper html to create a label within my webapp so that the pages are lighten of code and clear to anyone viewing the code.
Id like to avoid, having to <?php ?> for very simple boolean if
Any one know what I am looking for ?
static function User($UserObj,$isLink = true){
?>
<div class="image label bg-purple" style="margin: 4px;">
<?php if($isLink){
?><a href=""><?php
} ?>
<img src="<?php echo $UserObj -> ProfilePicture; ?>" style="height: 2em;" class="img-circle" alt="User Image">
<label style="font-size: 90%"><?php echo $UserObj->FirstName{0}.$UserObj->LastName{0}; ?></label>
<?php if($isLink){
?></a><?php
} ?>
</div>
<?php
}
Edited
After some more research by going through PHP documentation on Operator
I found Nowdoc string quoting
Can someone shed some light onto Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
Its good that you added code to your question so that we can all see what you are dealing with here. Now to me what I understand with your question is that you want to avoid using php tags to echo some html code based on if condition.
<?php
static function User($UserObj,$isLink = true){
$html = '<div class="image label bg-purple" style="margin: 4px;">';
if($isLink) $html .= '<a href="">';
$html .= '<img src="'.#$UserObj->ProfilePicture.'" style="height: 2em;" class="img-circle" alt="User Image">';
$html .= '<label style="font-size: 90%">'.#$UserObj->FirstName[0].#$UserObj->LastName[0].'</label>';
if($isLink) $html .= '</a>';
echo $html;
}
?>
In my thinking I thought you should just have to run php tags once and use a simple variable to add your html code to so that you can print at the end of the function.
I didn't understand some of your images but all the same your issue is printing unescaped html in PHP. In other words you want to have raw html.
There are two functions am thinking of right now which you can use depending on your desired output: html_entity_decode() and htmlentities().
html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.
<?php $orig = "I'll \"walk\" the <b>d
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk&quot
echo $b; // I'll "walk" the <b>
?>
Ref: http://www.php.net/html_entity_decode
I hope this helps solve your issue of unescaped html.

Get the .html after the echo

How to get the link of .html after the .$obj->product_name. ?
I have tried it as bellow. But it only shows the link of http://.com/forbiden insted of http://.com/forbiden rice.html where it cuts the rice.html
echo '<span class="product-name"><a href=products/'.$obj->product_name ."html". 'target=_blank>'.$obj->product_name.'</a></span></br>';
Try with urlencode($obj->product_name)
Hope that helps :)
Attribute values containing spaces must be quoted in HTML (and it is good practise to always quote your attribute values).
The space between forbiden and rice is terminating the attribute value.
URLs aren't allowed to have spaces in them anyway, so you should run the string through urlencode too.
You'll find it easier to deal with the quotes if you break out of PHP mode to output HTML instead of trying to mash it together in strings.
Also note that you should escape text content for HTML with htmlspecialchars as a defence against XSS.
$url = "products/" .urlencode($obj->product_name) . ".html";
?>
<span class="product-name">
<a
href="<?php echo htmlspecialchars($url); ?>"
target="_blank">
<?php echo htmlspecialchars($obj->product_name); ?>
</a>
</span>
<br>

how to add javascript/html codes inside php echo

I need the html td class inside the php echo for the javascript functionalities and scripts. The td class works well at first but when i insert it inside the php code it is not functioning anymore. Any ideas how to make it work?
Here is my code:
<?php
endforeach;
if($exist==1)
{
echo "
<tr>
<td>$date1</td>
<td>$m_time</td>
<td>$mx_time</td>
<td>$total_hrs</td>
<td class="tbl-save"><img onclick="save(this);" id="<?php echo $list->id ?>" class="icon-save" src="<?php echo base_url(); ?>images/save.png" width="15" height="15" title="Save"></td>
<td class="tbl-edit"><i onclick="edit(this);" id="<?php echo $list->id ?>" class="icon-pencil"></td>
</tr>";
}
else
{
}?>
The error occurs because you are using double quotes inside the echo statement, which terminate your string literal.
echo "<td class="something">";
^ ^
| |
The string PHP thinks that the
literal be- string literal ends
gins here here.
In order to use double quotes inside a string literal, you can use the following options:
Escaping the double quotes with a backslash: \". The double quotes will be interpreted as literal double quote, due to the preceding backslash.
Use single quotes to delimit the string:
echo '<td class="something">';
But there are alternatives:
Don't put HTML code in an PHP echo statement, only PHP variables:
<td><?php echo $date1; ?></td>
Bind your PHP variables to a custom template system and parse the output:
<?php
// Turn on output buffering. It will not send the output away,
// but hold it for later use.
ob_start();
?>
<td>%date%</td>
<td>%mtime%</td>
<?php
// Here we store the contents of the output buffer
// into a variable.
// The output buffer will contain this:
// <td>%date%</td>
// <td>%mtime%</td>
$contents = ob_get_contents();
// Now we need to replace some of our own custom
// variables with the PHP variables.
$search = array("%date%", "%mtime%");
$replace = array($date, $m_time);
$contents = str_replace($search, $replace, $contents);
echo $contents;
?>
The root cause of your problem is that the double-quotes around your class name are terminating the echo string. You will need to escape them with backslashes.
For example:
echo "<td class="tbl-save">"
Should be instead:
echo "<td class=\"tbl-save\">"
Alternatively you could use a HEREDOC and not worry about escaping double quotes. For example:
echo <<<END
<td class="tbl-save">
END;
You can read up more about HEREDOCs here: http://php.net/manual/en/function.echo.php
In general I would avoid mixing HTML and PHP as a best practice since it can make the code unyieldy to read and most IDEs lose the ability to syntax highlight the HTML inside your string. Consider using templating alternatives such as twing/smarty or MVC frameworks.
This wikipedia article lists the templating engines available you can choose from:
http://en.wikipedia.org/wiki/Comparison_of_web_template_engines
you cant do echo "... class="tbl-save"... "
it has to be echo "... class='tbl-save'..."
Use the escape slash () before all double quotes other than starting and ending double qoutes.
You need to escape the double quotes inside of echo ""; or use single quotes inside of it. Or you can change echo ""; to echo '';. The downside is you can't use variables inside, since they don't get parsed. You need to 'break' the string in order to use a variable echo 'use of variable '.$variable.' mkay';.
Also it's not necessary to do <?php echo $variable; ?>, since the variable anyway get parsed inside of double quotes and you didn't close the php tag before. But I would recommend you for the sake of readability to 'break' the string like above.
echo '
<tr>
<td>'.$date1.'</td>
<td>'.$m_time.'</td>
<td>'.$mx_time.'</td>
<td>'.$total_hrs.'</td>
<td class="tbl-save"><img onclick="save(this);" id="'.$list->id.'" class="icon-save" src="'.base_url().'images/save.png" width="15" height="15" title="Save"></td>
<td class="tbl-edit"><i onclick="edit(this);" id="'.$list->id.'" class="icon-pencil"></td>
</tr>';
No need to use nested <?php ?> tag. Use single quotes for echo '' and double quotes inside it (eg, id="id1" and so on..). Try something like below
if($exist==1)
{
echo '
<tr>
<td>$date1</td>
<td>$m_time</td>
<td>$mx_time</td>
<td>$total_hrs</td>
<td class="tbl-save">
<img onclick="save(this);" id="'.$list->id.'" class="icon-save" src="'.base_url().'images/save.png" width="15" height="15" title="Save">
</td>
<td class="tbl-edit"><i onclick="edit(this);" id="'.$list->id.'" class="icon-pencil"></td>
</tr>';
}
The syntax highlighter shows you what the problem is. Make sure your strings are properly escaped and terminated.
Also you have <?php tags within php strings.
<?php
endforeach;
if($exist==1)
{
echo "
<tr>
<td>$date1</td>
<td>$m_time</td>
<td>$mx_time</td>
<td>$total_hrs</td>
<td class=\"tbl-save\"><img onclick=\"save(this);\" id=\"{$list->id}\" class=\"icon-save\" src=\"".base_url()."images/save.png\" width=\"15\" height=\"15\" title=\"Save\"></td>
<td class=\"tbl-edit\"><i onclick=\"edit(this);\" id=\"{$list->id}\" class=\"icon-pencil\"></td>
</tr>";
}
else
{
}?>

Problem echoing this line in PHP

I am having trouble echoing this line. Is anyone willing to help?
echo '<li>'.$row->subject.'</li>';
As your string is enclosed in single-quotes, you have to close the quotes, concatenate the variables, and re-open the quotes :
echo '<li><a href="http://stackoverflow.com/thread-'
. $row->tid
. '-1-1.html">'
. $row->subject
. '</a></li>';
(split over several lines to improve readability)
Else, you could use a double-quoted string, to have variables interpolation -- escaping the double-quotes that are inside the string :
echo "<li>{$row->subject}</li>";
Your quotes are mismatched.
....'-1-1.html">'....
<?php
echo <<<_HTML_
<li>
{$row->subject}
</li>
_HTML_;
?>
You are echoing one single quote too much in the middle of this part: '-1-1.html'">'. This single quote is currently closing the string and will result in a parse error.
If your editor is supporting syntax highlighting, you will be able to notice a difference in colour after this quote.
To solve this problem, change this your code to:
echo '<li>'.$row->subject.'</li>';
?>
<li>
<a href="http://stackoverflow.com/thread-<?=$row->tid?>-1-1.html">
<?=$row->subject?>
</a>
</li>
like this:
echo '<li>'.$row->subject.'</li>';

a problem with heredocs syntax?

I have a problem with the syntax for a heredoc. Let me show the code first:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image=='NULL'){
//don't display image
}
else {
echo '<img src="userpics/$image" width="480" height="480">';
}
return <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
}
The $image variable comes from the database, it's either NULL or has a filename. If an image is null I don't want to display the <img> tag, if it does have a value then I want to show it. Do you know how I can solve this problem? I have been trying everything, but nothing has worked yet!! :))
If data in a MySQL database is NULL, you would check that with the is_null() function, not comparing to the string 'NULL':
function format($user_id,$user_note,$image,$dt)
{
if(!is_null($image)){
$image = "<img src=\"userpics/$image\" width=\"480\" height=\"480\">";
}
return <<<ENDOFRETURN
<div class ="commentbox">$date</div>
<div class="leftpanel">
$user_note
$image
<div class="date">$rel</div>
</div>
ENDOFRETURN;
}
Also, as others have mentioned, the end of the heredoc must not be indented.
EDIT: I just edited a few other things in your code and showed the whole function to give you a better idea.
I can see several problems with your code, but where the heredocs syntax is concerned, try removing the spaces before ENDOFRETURN;.
There are several problems, the correct way would be something like:
function format($user_id,$user_note,$image,$dt){
//this is the problem
if($image !== NULL){
$output .= '<img src="userpics/' . $image . '" width="480" height="480">';
}
$output .= <<<ENDOFRETURN
<div class ="commentbox">
$date
</div>
<div class="leftpanel">
$user_note
$image
<div class="date">
$rel
</div>
</div>
ENDOFRETURN;
return $output;
}
you see:
ENDOFRETURN; has no spaces before it
all output is returned in one ... return
For the sake of being thorough:
NULL is a keyword, just like: print, echo, if, for. Meanwhile,'NULL' (note the quotes) is a string, just like if you had typed 'if' (note the quotes, again) it would be a string, not the beginning of an if statement.
Your echo statement in single quotes as above, won't do what you intend it to. The variable $image will not be expanded in a single-quoted string. Reverse your single and double quoting instead as
echo "<img src='userpics/$image' width='480' height='480'>";
Also the ENDOFRETURN; at closing your heredoc must not have any spaces before it.
simply adjust
{spaces or tab}ENDOFRETURN;
to
{no spaces/tab}ENDOFRETURN;
rtm - exactly same problem as yours
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Categories