a problem with heredocs syntax? - php

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.

Related

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>

Options to maintain line breaks in PHP > HTML source code?

I'd like to keep my HTML source code pretty and indented (or tabbed). For instance:
$someHTML.='<div class="NOINDENT">';
$someHTML.=' <div class="INDENT1">';
$someHTML.=' <div class="INDENT2"><div>';
$someHTML.=' </div>';
$someHTML.='</div>';
echo $someHTML;
This PHP looks pretty and readable enough to me, but when the HTML is output it will be one long line of code (with no line breaks)! I'd like to have PHP print a line break, but still have the code "readable" while working on it in PHP.
For the above example, is using \n at the end of each line my only option?
Heredoc syntax to the rescue
$someHTML = <<<HTML
<div>
<div>
...
</div>
</div>
HTML;
you can use the constant PHP_EOL to end your lines
$someHTML.='<div class="NOINDENT">'.PHP_EOL;
The HEREDOC syntax is better, but when you are inside functions / loop / etc. which requires tabs, it make the php code looks weird sometimes
I try and avoid echoing html if its more than a single line.
Instead you can use output buffering if you need the html in a string, eg if you need to return a string from a function:
function getHtmlString(){
ob_start(); ?>
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
<?php
$html = ob_get_clean();
return $html;
}
?>
<html>
<head>...</head>
<body>
<div id="someid">
<?php echo getHtmlString(); ?>
...
Yes, you must add '\n' at the end.
And if you want tabs, add '\t' at the beggining of each line.
In order to use line breaks, you need to use the double-quoted string form and place a newline (\n) character at the end of every line. Note that the double quotes within the string now need to be escaped with a backslash. For example:
$someHTML.="<div class=\"NOINDENT\">\n";
$someHTML.=" <div class=\"INDENT1\">\n";
$someHTML.=" <div class=\"INDENT2\"><div>\n";
$someHTML.=" </div>\n";
$someHTML.="</div>\n";
echo $someHTML;
Another option would be to use the HEREDOC string format, which will maintain whitespace and also has the advantage of not requiring you to escape double quotes:
$someHTML = <<<HERE
<div class="NOINDENT">
<div class="INDENT1">
<div class="INDENT2"><div>
</div>
</div>
HERE;
I wanted to show that this solution is close to what I want , and works great, but the staring and ending ' and '; aren't that pretty. heredoc seems like the best and cleanest answer so far.
function html(){
$someHTML=
'<div class="NOINDENT">a
<div class="INDENT1">b
<div class="INDENT2">c<div>
</div>
</div>';
return $someHTML;
}
echo(html());

Interpret PHP inside a quote in a 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>
<?}?>

how to style php echo output

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.

How do I get this while loop to dynamically produce this html?

I am building a picture gallery, that uses this code to display each product I have:
<div class="feature">
<imagetag alt="Image Caption"srcs="">
<div>
<p>
This is some information that can go along with an image.
Anything can be placed here, including images.
</p>
</div>
</div>
I need to create a while loop, that takes all the products in my database, and creates a div of the "feature" class for every instance. I have problems know exactly which symbols need to be escaped and etc. Your help is greatly appreciated.
here is my start:
<?php
($product_set = mysql_fetch_assoc($query)) {
print("<div class="feature"> <imagetage alt="Image Caption" srcs=$product_set[products_image]>"
);}
?>
If you are in a string, every doublequote should be escaped. Because it will close your string.
<?php
($product_set = mysql_fetch_assoc($query))
{
print "<div class=\"feature\"><img alt=\"Image Caption\" src=" . $product_set['products_image'] . ">";
}
?>
Fun thing is, I got a link from someone on stackOverflow about PHP templating. Which was using Smarty. So you don't have to use these print states anymore.
Have you tried:
print(htmlentities($my_html_string))
or htmlspecialchars? htmlentities converts all characters that have one to their HTML escape sequence, while htmlspecialchars converts only those that have meaning in HTML.

Categories