for example i want to generate html code, using some data from database.
here is two ways of printing data
<? echo '<li><img src="'.$row['image'].'" /></li>';?>
or
<? echo "<li><img src='$row[image]' /></li>";?>
both of them are working. and if so, why people use the first method, if without spliting the row by . it works fine too.
thanks
The best way would be to use only one method.
I'd even use <?php echo '<li><img src="' . $row['image'] . '" /></li>'; ?>
There's a speed difference, but that would be barely measurable and usually not at all noticable. Every string in double quotes is parsed first. That's why it's better to not use double quotes for strings at all. If you use extremely many strings with vars in it, it could become a measurable difference - but doing that would be quite bad design in the first place.
Btw.: The same is true for often switching the parser on and off with <?php and ?>.
The main reason for doing the above is good coding practice.
Others may need to understand your script too. And maybe yourself too some years later.
Vars in strings can be easier overlooked than vars included like this.
Even more so on IDEs with syntax highlighting.
I've even seen people put a newline before every var inserted in this way. But IMHO that's a little too much. ;)
More or less offtopic: No I didn't read all the fighting going on in the other answers, but I know the old "no it's not slower" vs. 'Yes it is' kindergarden by heart. ;)
For christs sake, you're coders, damnit. Just test it:
<?php
$startt = microtime(true);
for ($i = 0; $i <= 10000000; $i++) {
$test = 'This is test number ' . $i;
// $test = "This is test number " . $i;
// $test = "This is test number $i";
}
$endt = microtime(true);
echo 'Used time: ' . ($endt - $startt);
?>
For me the first one gave 5.1321198940277, the second one 5.2075009346008 and the third one 6.4821639060974 (more than 1.2 secs difference). Q.E.D. so far.
The interesting thing would be to try that on different systems. Maybe I'll make my own question for this.
echo sprintf('<li><img src="%s" /></li>', $row['image']);
Much easier to read and less prone to errors if it get's changed/extended later.
Another method:
<li><img src="<?php echo($row['image']); ?>" /></li>
<? echo '<li><img src="'.$row['image'].'" /></li>';?>
A reasonable strategy is to output all static content in plain PHP templating. That way you don't have to worry about PHP string literal escaping in the static content:
<li><img src="<? echo $row['image']; ?>"/></li>
However, (a) you need to use htmlspecialchars() on all raw-text strings output into HTML, or you've got potential cross-site-scripting issues. Also, <? short tags should generally be avoided as they may not be enabled on all servers.
To cut down on the amount of typing “htmlspecialchars” in templates, define a shortcut function:
<?php
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<li><img src="<?php h($row['image']); ?>"/></li>
In the second method:
<? echo "<li><img src='$row[image]' /></li>";?>
you cannot use functions, you can only use variables. It does not matter which method you use if you are printing variables.
the fastest way is to call the echo function with multiple parameters instead of a string that contains the concatenated parameters:
echo '<li><img src="',$row['image'],'" /></li>';
is the equivalent of
echo '<li><img src="';
echo $row['image'];
echo '" /></li>'
which is faster than
echo '<li><img src=";'.$row['image'].'" /></li>';
If you are using ' in your html tags for specifying attribute values then use " in PHP and if you are using " in html then use '. Either way you won't need to escape the quote in html by \
Related
How do I include a php tag in an HTML attribute? I still find it quite tricky.
This is the HTML attribute:
src="https://customer.site.com/?language=en_US&portal=Default"
The thing is, ?language should accept a dynamic value. That value is stored in $lingos[$wmpl_langcode].
So I've been trying many variations and I'm still stuck.
I've got this now but it doesn't seem right.
src=<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
I don't want to waste any more time on it. Any tips would be great.
you was just missing one double quote and the ; at the end of the echo to end the instruction:
src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode]; ?>&portal=Default"
You are now missing quotes for the attribute.
This however would be perfectly fine:
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
If you like it a bit more clean without confusing quotes:
<img src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode] ?>&portal=Default"/>
You should also think about urlencode():
<img src="https://customer.site.com/?language=<?php echo urlencode($lingos[$wmpl_langcode]) ?>&portal=Default"/>
To make it "more clean", you should use a templating engine.
When you directly use echo to print the dynamic link, the quotes are not present there.
Try this:
src="https://customer.site.com/?language=<?=$lingos[$wmpl_langcode] ?>&portal=Default"
OR
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
Ive started on part of my new year resolution and decided to learn php, as part of it im trying to parse in an xml feed, and echo out the name of the events wrapped in <a> tags linking them back to the events page on the xml feed's site.
I think ive got it all in but i cant seem to see why this isnt working im just getting a blank page, if some one could point me in the right direction it would be much appreciated, cheers
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href="$event_attributes['url']">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
</ul>
echo "<a href="$event_attributes['url']">";
try changing that line to
echo "<a href=\"".$event_attributes['url']."\">";
The Php parser is pretty funny about this. Usually you pick one and just stick to it, or use both single quotes and double quotes as you please. Just remember that strings with double quotes are parsed for variables.
$hello = "Hello";
echo "$hello master";
is the same as
$hello ="Hello";
echo $hello.' master';
When you are testing your PHP scripts, you'll find it useful to switch on errors - then PHP will actually tell you why it isn't showing you anything:
error_reporting(E_ALL);
Normally you will have missed a ; or mis-typed a variable name.
in your case the error is here:
echo "<a href="$event_attributes['url']">";
You have accidentally ended the string with a double quote, so PHP thinks the string ends here:
echo "<a href="
This is where using single-quotes can be very handy because your double quotes won't then close the string.
echo '<a href="' . $event_attributes['url'] . '">';
The main difference between single and double quotes in PHP is that double quotes has special clever parsing rules and single quotes doesn't. For example:
$myVar = "BLAH";
echo "Example $myVar"; // Example BLAH
echo 'Example $myVar'; // Example $myVar
In your unordered list, you should use a dot to concatenate your string, and escape your double quotes like this:
echo "<a href=\"".$event_attributes['url']."\">";
Instead of
echo "<a href="$event_attributes['url']">";
Your example throws and error because you haven't used proper string concatenation. However, even with correct concat, it would render as <a href=http://someurl>, and you'd need to add the double quotes according to html standard. Hence you have to double quote.
if you want to not be troubled by having to switch between using a ' or a " then i suggest using the php alternative syntax php alternative syntax
with the given code it would look like
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php foreach($type->market as $event):?>
<li>
<a href="<?php echo $event_attributes['url']; ?>">
<?php echo $event_attributes['name']; ?>
</a>
</li>
<? endforeach;?>
</ul>
one advantage this would bring is that it would produce cleaner code since you can clearly distiguish your php code from your html which is the presentational part at the price writing all those other <?php ?> and as what others would claim a performance degradation. the choice is yours
Change
echo "<a href="$event_attributes['url']">";
for
echo "<a href=".$event_attributes['url'].">";
You are missing the periods in your second echo, where you have your $event_attributes['url']
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href=".$event_attributes['url'].">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
I would recommend you to enable your error log, it would allow you to know the line with problems in any of your scripts.
I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.