how to add javascript/html codes inside php echo - php

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
{
}?>

Related

What's wrong with this line ? i'm trying to figure out since hours (php)

The following line of code is supposed to echo the current season and a data in a php echo:
<?php echo "<h5>" $_SESSION['username'] '<span class="chat_date">'Dec 25"</span></h5>" ?>
Is the session call true? And how can I fix this code?
if you want echo a string you should use concatenation operator ('.')
<?php echo '<h5>' .$_SESSION['username']. '<span class="chat_date">Dec 25</span></h5>' ?>
or use double-quotes (") to passing data
$usename=$_SESSION['username'];
<?php echo '<h5>"$usename"<span class="chat_date">Dec 25</span></h5>' ?>
There is no need to concatenate a string before echoing it in PHP.
The parameters can be passed individually to echo as multiple arguments for a slight performance (speed) increase. In other words, you can use , instead of ..
For example:
<?php echo '<h5>' , $_SESSION['username'] , '<span class="chat_date">Dec 25</span</h5>'; ?>
I would recommend reading the Official Documentation.
<?php
echo "<h5> $_SESSION[username] <span class=\"chat_date\">Dec 25</span></h5>";
?>
Variables are evaluated inside double quoted strings.
To echo double quotes inside double quotes, you add a backslash before the double quote so PHP knows it is not the end of the quoted segment.
For arrays, do not quote the key inside a string.

String manipulation in Mixed HTML and PHP code

The code below is a sample code of the top oh my php web page. There are php variables being outputted in specific places.
I'd to implement an HTML to PDF converter, but it requires me to put all of my code into a single variable that the PDF converter will use in its class. How can I put my existing into into a single variable say: $html without having to open up all my PHP variables, escpaing everything and concatenating the whole place? I was thinking of using heredocsyntax but it doesn't like the <?php ?> and I'm sort of confused as I've never used it in the past. Any ideas on how to achieve this?
Ideally, this is what I'd like to do:
$html = <<<EOD
<div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
EOD;
The above doesn't capture any values outputted by $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] or by configuration::getValue(6).
Insead of:
$html = "";
$html .= "<div id=\"topHeaderView\">".configuration::getValue(6)."</div>";
$html .= "<table>";
$html .= "<tr>";
$html .= "<td>".$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]."</td>";
$html .= "</tr>";
This is something I want to avoid...
This is a good use of output buffering
ob_start();
?><div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
<?php
$html = ob_get_clean();
As far as I can see in the manual, it is not possible to call functions inside HEREDOC. A less cumbersome solution is:
$config_print = configuration::getValue(6);
$lang_print = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$config_print</div>
<table>
<tr>
<td>$lang_print</td>
</tr>
EOD;
Edit: Or you could use:
$html = <<<EOD
<div id="topHeaderView"><?= _( configuration::getValue(6) ); ?></div>
<table>
<tr>
<td><?= _( $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] ); ?></td>
</tr>
EOD;
heredoc is php syntax therefore it needs to be inside the php tags. The php documentation, here, explains the behavior of variables within heredoc strings:
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped... Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
There are also some examples in the documentation.
<?php
$value = configuration::getValue(6);
$header = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>$header</td>
</tr>
EOD;
?>
The manual has a whole chapter devoted to the assorted string syntaxes that PHP provides (4 to date). You're basically missing string interpolation:
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>{$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]}</td>
</tr>
EOD;
Fiddle
However, it isn't as simple as that. You are using PHP to generate code in another language (HTML) and you need to ensure that the resulting code is valid. Thus you cannot inject random stuff. In order to insert literal text inside HTML you need to use htmspecialchars(). And variable interpolation expects, well, variables, not functions. So the heredoc syntax offers little advantage here. Concatenation would be a simpler alternative:
$html = '<div id="topHeaderView">' . htmlspecialchars($value) . '</div>
<table>
<tr>
<td>' . htmlspecialchars($lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]) . '</td>
</tr>';
You said you don't to escape and concatenate. I understand you. That's why complex HTML generation normally relies on template engines. Find one or build your own.

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;

Categories