String manipulation in Mixed HTML and PHP code - php

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.

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.

PHP variable hooks

i was wondering what the difference is when u put a variable in another variable with the notation. So i have a variable "Body" and in there is HTML tags, text and PHP variables, ive found out i can put them in between hooks but that they would react exactly the same. Example:
In this piece of code the variable is in between { } hooks.
$body = "
<table style='border: 1px;'>
<tr>
<td><b>Naam:</b></td><td>{$naam}</td><br>
</tr>
</table>"
And here it is not.
$body = "
<table style='border: 1px;'>
<tr>
<td><b>Naam:</b></td><td>$naam</td><br>
</tr>
</table>"
And this both reacts exactly the same. So can anyone tell me if this has an actual use, or that this is just like all PHP with the 10 ways to do the same thing.
Thanks in advance.
Addition
This is not a duplicate ofThis. It does not explain the part of why a variable inside of a variable can be put in between curly brackets.
Usage of curly braces inside " is particularly useful when you want to add complex instruction or access object/array properties.
This code will perfectly work
<?php echo "Test {$foo['bar']}"; ?>
<?php echo "Test {$foo->bar}"; ?>
While this one will fail
<?php echo "Test $foo['bar']"; ?>
<?php echo "Test $foo->bar"; ?>
So yes, it's not particularly useful if you are accessing a simple variable, but when you want to play with array and object, it's useful.

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

Setting a CSS element class in PHP

I'm trying to modify a bit of PHP code to get it to assign a unique CSS class to the elements it creates as it cycles through its loop. Theoretically, I'm just trying to take a "name" that's echoed to the screen and assign that as a class to a element that's created next... Here's the intitial relevant code loop:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Simplistcally, I'm trying to get the string that's echoed by $exam->name to be assigned to the class of that <tr> element. Something like
<tr class="<?php echo $exam->name;"><td><?php echo $exam->name;?></td></tr>
Although I'm sure I'm handling the quotes or syntax improperly (at least, anyway, it doesn't end up assigning the class to the <tr>.
It will help if you stop going in and out of PHP so much, it will probably be easier to read this way:
<?php
foreach($my_exams as $exam){
if($exam->is_taken){
echo '<tr class="'.$exam->name.'"><td>'.$exam->name.'</td></tr>';
}
}
If you want to do double quotes, you need to escape them when you want to echo them, but then you can use a variable without concatenating a bunch of strings. (Once you are using objects/arrays it helps to surround each variable with {})
echo "<tr class=\"{$exam->name}\"><td>{$exam->name}</td></tr>";
Reference: http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
<tr class="<? echo $exam->name ?>"><td><? echo $exam->name ?></td></tr>
Others have answered this pretty much the same way I am about to, but I want to add this to explain the issue. And why this is not a “stupid” question, but more of a bizarre byproduct of the way that some CMS system mix HTML & PHP within their templates. In short: They format the template as nice HTML to make it seem clean & easy for non-coders, but in doing so their mixing of inline-PHP makes PHP coding seem more difficult than it is. Meaning this code:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Can easily be this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo '<tr><td>'
. $exam->name
. '</td></tr>'
;
}
}
?>
Which is now easier to parse from a programming standpoint, so you can now do this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo sprintf('<tr%s><td>', ' class="' . $exam->name . '"')
. $exam->name
. '</td></tr>'
;
}
}
?>
What I did there is use sprintf to place ' class="' . $exam->name . '"' into the ''. The %s means that is a string that should be placed there, and the string is what comes after the comma in the sprintf statement. I find this much easier to code, test & debug. But in general, the key to making PHP coding easier is to just use straight PHP when any logic needs to be placed in the context of HTML.

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.

Categories