Is there a better way to output data to html page with PHP?
If I like to make a div with some var in php, I will write something like that
print ('<div>'.$var.'</div>');
or
echo "'<div>'.$var.'</div>'";
What is the proper way to do that?
Or a better way, fill a $tempvar and print it once? like that:
$tempvar = '<div>'.$var.'</div>'
print ($tempvar);
In fact, in real life, the var will be fill with much more!
There are 2 differences between echo and print in PHP:
print returns a value. It always returns 1.
echo can take a comma delimited list of arguments to output.
Always returning 1 doesn't seem particularly useful. And a comma delimited list of arguments can be simulated with multiple calls or string concatenation. So the choice between echo and print pretty much comes down to style. Most PHP code that I've seen uses echo.
printf() is a direct analog of c's printf(). If you're comfortable in the c idiom, you might use printf(). A lot of people in the younger generation though, find printf()'s special character syntax to be less readable than the equivalent echo code.
There are probably differences in performance between echo, print and printf, but I wouldn't get too hung up on them since in a database driven web application (PHP's typical domain), printing strings to the client is almost certainly not your bottleneck. The bottom line is that any of the 3 will get the job done and one is not better than another. It's just a matter of style.
you can even write
$var = "hello";
echo "Some Text $var some other text";
// output:
// Some Text hello some other text
or
print("Some Text $var some other text");
// output:
// Some Text hello some other text
doesn't make big difference. This works with double-quotes only. With single quotes it doesn't. example:
$var = "hello";
echo 'Some Text $var some other text'; // Note the single quotes!
// output:
// Some Text $var some other text
or
print('Some Text $var some other text'); // Note the single quotes!
// output:
// Some Text $var some other text
Just try this you gonna love the well formated amount of infos :
<?php
echo '<pre>';
var_dump($your_var);
echo '</pre>';
?>
OK, I explain : set a "code" html format and var_dump show the value, the type, the params ... of the variable.
http://us2.php.net/echo
<div><? print($var); ?></div>
Or if you don't have short tags on, you might need to
<div><?php print($var); ?></div>
if you have the short_open_tag option enabled you can do
<?=$var?>
But some find that messy.
You can also use the following syntax:
echo <<<ENDOFTEXT
<div>
$var
</div>
ENDOFTEXT;
Just make sure the ENDOFTEXT is not indented.
You could do something like this:
<div><?php echo $var; ?></div>
One of the nice things about PHP is that you can insert it into regular HTML, and accomplish things like the above with ease. I've always used echo myself in PHP. Not sure if it's the "proper" way, but it's the easiest.
While echo and print are almost equal, you a using different values. Your first value will result in
<div><value of $var><div>
while the second will result in
'<div>'.<value of $var>.'<div>'
But the rest is semantically almost equal. Since echo and print are no real functions but special language constructs, the parenthesis in your first example is just wrapping the single string value and not the parameter list.
See also https://stackoverflow.com/questions/1462581#1462636 and https://stackoverflow.com/questions/1163473#1163793.
I have read somewhere that echo is faster that print. But its just too small of a performance gain.
Related
Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>
Is there any advantages/disadvantages to either of these statements over the other one:
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
echo "<p>Hello World</p>";
?>
OR
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
?>
<p>Hello World</p>
What i'm asking is, if i'm outputting a page using PHP should i keep closing the php tags and stick normal HTML in or echo out the HTML? Which is better?
if you want do be realy exact, there are three options:
the slowest:
echo "<p>Hello World</p>";
a bit faster (no need to check for inline-valiables because of single quotes):
echo '<p>Hello World</p>';
the fastest (no php-interpreting at all):
<p>Hello World</p>
but between all of this, the difference would be so minimalistic that you won't ever notice it - much more important: make your code redable and do it the same way everywhere, so nobody who's reading your code (and has to maintain it) gets confused. i personally would prefer the third method (so i can use code-completition in my IDE), but it's your choice - i know a lot of people who output everything using echo.
EDIT: to be complete, there are some more possibilitys i didn't mentioned like heredoc- and nowdoc-syntax, but this are basically the same as double/single-quotes... also, you could write print instead of echo and so on, but that wouldn't make a difference.
Method 2 is cleaner IMHO because you separate PHP code from HTML. Your IDE (if you use any) can parse your HTML tags and autocomplete them, and spot any typo's.
I'm not a PHP programmer but I would assume the 2nd method is faster, because PHP doesn't have to process the echo language construct, allocate buffer and all that stuff. It is also cleaner, and less of a hassle to modify the HTML.
Also, it would be wise to learn to use a template engine for your HTML in order to separate concerns. Smarty was popular a couple years ago, I don't know if it's still is.
Although the difference is negligible, you should stick normal outputing out of PHP tags. Echo command will have to be parsed by PHP interpreter and then sent as output.
The only difference is that with echo(); you instruct PHP to process the code, otherwise, there is no difference at all.
One way or another, the result is exactly the same and for performance, there is almost no differences at all. Like... How much time PHP needs to process that echo();? I think with miliseconds you could run in problems calculating numbers that small. Hehe.
How can I print the array in a Tree-like format--making it easier to read?
Try:
<pre><?php print_r($var); ?></pre>
It will give the proper tree structure that HTML's whitespace policy trims out.
Are you wrapping the output in <pre> tags? That should get you pretty decent output, because it will show the spaces. Another option would be to install the xdebug extension, which then can replace var_dump so that it generates more-readable HTML output.
function pr($var)
{
print '<pre>';
print_r(htmlspecialchars($var));
print '</pre>';
}
pr($myArray);
I found it's a good idea to print_r as follows
printf("<pre>%s</pre>", print_r($array, true));
It may not be ideal, but it's easier to read.
Try taking a look at Zend_Debug, a relatively plug-and-play module from the Zend Framework which does an excellent job at effectively dumping complex variables.
Usage:
$my_var = new StdObject(); // or whatever
Zend_Debug::dump($my_var);
die; // optional, prevents routing, forwarding away, etc.
You could print it into the error log:
error_log(print_r($myarray,1));
Note that you will see \n instead of carriage returns because it has to be collapsed in a single line.
Mabe the output looks like junk in the webpage. Try looking at the source of the page and it will be in tree-like format I suppose.
As many people previously mention, make sure to wrap it around a <pre> tag.
I would take an extra precautions to make sure nothing is wrapping that <pre> as well, such as <p> or <div> with a CSS class that can override the Pre's Style
May I suggest using var_export($array)?
It formats values with parsable php syntax
And even when you forget to output <pre> and </pre> tags,
while not very easy on the eye,
its output still makes more sense then print_r informal bunch of data.
I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
<?php
echo '<html'>;
?>
vs.
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
I assume by "breaking out" you mean:
<?php foo(); ?>
test
<?php bar(); ?>
as opposed to
<?php
foo();
echo("test");
bar();
?>
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine.
I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
can be more readable than:
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
and with some IDEs (or stackoverflow.com syntaxhighlighting for example), it can even be more readable to use:
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
In summary:
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is most readable/maintainable and use it consistently.
If by breaking out you mean this sort of thing:
<?php
if($somecondition) {
?>
<!-- Some HTML -->
<?php
}
?>
Then yes, breaking out is better in most cases as it is more readable (many IDES highlight HTML syntax, and cannot do so if it is withing a string when being echo() ed)