how to style php echo output - php

It's probably stupid question, but I can not find an answer. How can I style echo output with css? I have this code:
echo "<div id="errormsg"> Error </div>";
Now it displays syntax error, I think because of those quotes around errormsg. I've tried single quotes, but with no effect. Thank you

When outputting HTML, it's easier to use single quotes so you can use proper double quotes inside like so:
echo '<div id="errormsg"> Error </div>';
That will get rid of your parse error... To edit the style you will need to use CSS with the selector of #errormsg like so:
#errormsg {
color: red;
}

try
echo "<div id=\"errormsg\"> Error </div>";

First you need to either use single-quotes to surround the attribute value:
echo "<div id='errormsg'> Error </div>";
Or you could reverse that, to give:
echo '<div id="errormsg"> Error </div>';
Or you should escape the quotes:
echo "<div id=\"errormsg\"> Error </div>";
And then style the resulting element with the CSS:
#errormsg {
/* css */
}
The syntax problem you were encountering is a result of terminating the string and then having a disparate element between the first and second strings, with which PHP has no idea what to do.

To put double quotes inside of a double-quoted string, you need to "escape" them by putting blackslashes before them:
echo "<div id=\"errormsg\"> Error </div>";
In this case, another choice is to use single quotes for one or the other.
echo "<div id='errormsg'> Error </div>";
echo '<div id="errormsg"> Error </div>';
PHP's documentation has a section explaining the different string syntaxes, which should explain everything you could want to know about this subject.

Use single quotes around errormsg and what you have should work just fine. Alternatively, but less tidy, you can escape the double quotes with a backslash.
echo "<div id='errormsg'> Error </div>";

You are getting a syntax error because you are including unescaped double quotes inside a string that is delimited by double quotes.
Either escape them
echo "<div id=\"errormsg\"> Error </div>";
or use single quotes
echo '<div id="errormsg"> Error </div>';
The browser doesn't care if you generated markup using echo or something else. It just sees the HTML you send to it.
For the above markup, you can style it using an id selector:
#errormsg { /* … */ }
The usual rules for the cascade (including specificity) will apply.

If you don't want to care about single quotes or double quotes then the better way to achieve your answer is to use heredoc syntax .
Your solution :
<?php
$heredoc = <<< EOT
<div id="errormsg">Error solved</div>
EOT;
echo "$heredoc";
?>
css :
#errormsg{color: green;}
WARNING :
Do not add whiteSpace after <<< EOT
Do not add whiteSpace before EOT;
Do not add whiteSpace between EOT and ;
Do not add whiteSpace after EOT;
EOT; must be in new line.

Related

Single quote within single quotes PHP

I have a HTML achor tag like below:
echo '<a href="javascript:tempBuy('.$res_get_price[0][0].','.$res_get_price[0][1].','.$res_get_price[0][2].','.$dt_str.')">'.$res_get_price[0][0];
And the corresponding javascript function tempBuy() is
function tempBuy(rate,veg_name,market_name,dt)
{
alert(dt);
}
But the problem is it does not alert at all ! May be I need to include the variable names within single quotes in tempBuy() function. I tried tempBuy(\'var1'\,\'var2\'...) but it shows error. How can I able to to that. Thanks .
Source for the part shows like this:
<td width="120px" class="">56.0
</td>
<script>
function tempBuy(rate,veg_name,market_name,dt)
{
alert(rate);
}
</script>
You didn't wrap your javascript arguments in quotes. You need to wrap each variable in single quotes, since you used double quotes for "href" attribute. Another thing is that you didn't close up "a" HTML tag.
echo ''.$res_get_price[0][0].'';
If there is anything in your variables that is not a valid javascript literal you have to make it a string like:
echo '<a href="javascript:tempBuy(\''.$res_get_price[0][0].'\' ...
If there are ' in your variables you have to replace them with \' as well.
As you can see form the rendered output, you need to quote the last 3 arguments which are non-numeric. The correct output should be: javascript:tempBuy(56.0,'Apple','Bangalore','2013-05-18')
The corrected PHP code is:
echo ''.$res_get_price[0][0].'';`
echo "<a href=\"javascript:tempBuy('".$res_get_price[0][0]."','".$res_get_price[0][1]."','".$res_get_price[0][2]."','".$dt_str."')\">".$res_get_price[0][0];

PHP - hyperlink tag not showing full value of the variable

i am trying the following code in order to get the tag value to both in anchor and title. but code is ok with anchor text but showing only single char in title..
$tag=$info['name']." from ".$info['city'];
echo' <td class="title1" bgcolor="#F7F7F7"> <a title='.$tag; echo' href=details/';
echo $info['friendly_url'];
echo' >';
echo $tag;
echo'</a></td>';
please note that the tag value is something like "David from NW";
Thanks for your help.
You need quotes around the title value, otherwise the parts after the space will be interpreted as a (malformed) HTML attribute.
echo '<td class="title1" bgcolor="#F7F7F7">';
echo '<a title="'.$tag.'" href="details/' . $info['friendly_url'] . '">';
echo $tag;
echo'</a></td>';
It is good practice to use quotes to surround your HTML attributes to avoid situations like this.
That is butt-ugly code. Repeated echoes get to be impossible to maintain in short order. You could use a HEREDOC and make it pretty/legible at the same time:
echo <<<EOL
<td class="title1" bgcolor="#F7F7F7">
<a title="$tag" href="details/{$info['friendly_url']}">$tag</a>
</td>
EOL;
Any modern PHP-aware IDE will properly color the variables. And note how you can use quotes and variables within the heredoc, without having to do any nasty string concatenation.

How to PHP echo when using multiple quotes

How should I quote this:
<tr onclick="$.colorbox({href:'information1.html'});">
When put in an echo " "; ?
I have tried this:
echo "<tr onclick='$.colorbox({href:'information1.html'});'>";
Which shows a Jquery error.
And I tried this:
echo "<tr onclick="$.colorbox({href:'information1.html'});">";
Which shows a PHP error.
Any workarounds? Thanks
You need to escape the quotes symbols:
echo '<tr onclick="$.colorbox({href:\"information1.html\"});">'
Note that using inline script is not considered to be a good practice!
echo '<tr class="foo">'
In the javascript code:
$('.foo').click(function() {
$.colorbox({ href: "information1.html" });
});​
Simply escape the quotes. Whilst on this subject I feel it important to mention the fact that generally speaking, you should use single quotes for 'code' and double quotes only for displayed strings.
This stems from C standards and keeping this consistent will help you in the future if for example you wanted to implement gettext() and translate your website into multiple languages.
echo '<tr onclick="$.colorbox({href:\'information1.html\'});\">';
Having said that, there's a better way to achieve what you're doing. Give the row an id:
<tr id="inforow" />
And use jQuery to bind to it's click event when the DOM is ready.
$(document).ready(function() {
$(".inforow").click(function() {
$.colorbox({href:'information1.html'});
});
});
Anytime you want to print a string with a quote in it, just use the escape character '\' to ignore the quote as a literal closing quote, like so:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
Try that:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
I would use PHP-methods instead of caring about the quotes
echo '<tr onclick="'.
htmlentities('$.colorbox('.json_encode(array('href'=>'information.html'))).')">';
...will always create proper JSON and proper HTML, no matter what characters you use.
NO NEED to quote it.
NO NEED to put in an echo " ";
Just leave it AS IS:
?>
<tr onclick="$.colorbox({href:'information1.html'});">
<?
as well as any other HTML.
It's PHP. It's embedded in HTML. You can leave PHP mode any time
Another way is using EOD
$string = <<<EOD
"duble quotation" and 'quotation' all enable
EOD;
echo $string;

Problem escaping php variable

I'm having trouble escaping the PHP variable inside the getItems function:
while($row = mysql_fetch_array( $data ))
{
echo "<div class='favorite'>";
echo "<div style='display: inline;'>".$row['Item']."</div>";
if ($row['UID'] = $uid) {
echo "<div id='unlock'>Info</div>";
} else {
echo "<div id='unlock' onclick='getItems('".$row['Item']."')'>Unlock</div>";
}
echo "</div>";
}
When rendered (is render the word?) anyway, when I see it on my site it says:
onclick="getItems(" whatever')'
What am I doing wrong?
You can see the code here:
http://www.chusmix.com/game/insert/get-items.php?user=19
Your problem is that your attribute values are surrounded by single quotes, but you're also using single quotes in your javascript.
You'll have to use double quotes in your javascript. However, since the whole string (in PHP) is surrounded by double quotes, you'll have to escape them. Hence:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\")' style='display: inline; float: right;'>Unlock</div>";
Or like this:
echo "<div id='unlock' onclick='getItems(\"{$row['Item']}\")' style='display: inline; float: right;'>Unlock</div>";
To clarify what the curly braces do (from the PHP docs):
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }.
To further explain, let's say we have the following scenario:
$name = 'Apple';
$sentence = "$names are my favorite fruit";
What I'm trying to get is: Apples are my favorite fruit. However, this won't work. PHP will instead be looking for a variable called $names, and when it doesn't find it, it'll complain.
So, to remedy this, we can surround our variable in curly braces:
$name = 'Apple';
$sentence = "{$name}s are my favorite fruit";
Great! Now PHP will know where the variable name ends and the string starts.
On a side note: You might consider switching to double-quoting your attributes, since the way you do it now is not valid xHTML (unless you don't care).
Yes, there is a problem with your quotes. It should be this:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\");' style='display: inline; float: right;'>Unlock</div>";
The problem is that your opening quotes for onclick and the quotes around the function arguement have to be a different kind of quote.
This is much easier though to do with html and then just insert the variable like this:
<div id="unlock" onclick="getItems('<?=$row['Item'];?>');" style="display: inline; float: right;">Unlock</div>
Doing things this way instead of echoing HTML when possible will save you tons of time and confusion, and you won't have to worry about all the escaping of quotes
The ' inside onclick is closing the onclick itself. Change it to:
onclick='getItems(\"".$row['Item']."\")'
That way, in JS, it uses a different type of quote.
Even better... you can leave PHP, and have one less type of quote to worry about.
else { ?>
<div id='unlock' onclick='getItems("<?=$row['Item'];?>")' style='display: inline; float: right;'>Unlock</div>
<?php
}
or like so:
echo '<div id="unlock" onclick="getItems('."'".$row['Item']."'".')" style="display: inline; float: right;">Unlock</div>';
If I had to do this, it would have looked like:
<?php while(true) :?>
<div class="favorite">
<div style="display: inline;"><?php echo $row['Item'];?></div>
<?php if ($row['UID'] = $uid):?>
<div id="unlock">Info</div>
<?php else: ?>
<div id="unlock" onclick="getItems('<?php echo $row['Item']; ?>)">Unlock</div>
<?php endif;?>
</div>
<?php endwhile;?>
try the following .
edit: changed to make sure quotes were escaped correctly
echo "<div id='unlock' onclick=\"getItems('{$nameArray[0]}')\" ></div>";

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>';

Categories