I wrote a code involving nested PHP and HTML parts as below. Why variable "v" is not displayed, But the variable "u" is?
<?php
$v= rand (1,15);
$u= rand (1,15);
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
<?php echo $v ?>
</body>
</html>
EOD;
echo $h;
?>
<html>
<body>
u=<?php echo $u ?>
</body>
</html>
PHP has two modes.
Inside <?php...?> (and other PHP tags) PHP code is evaluated
Outside those tags, code is streamed directly to the output
You have <?php echo $v ?> inside a PHP section (inside a string created with HEREDOC).
It doesn't trigger PHP evaluation of the content when the string is created because it is just part of the string. It doesn't trigger PHP evaluation when you later echo it because you are just echoing a string.
<?php echo $v ?> will be in the (invalid) HTML sent to the browser, and the browser will treat it as an unknown tag. The value of $v will be one of the attributes. The browser won't render anything for this unknown tab, but you will be able to see it in the Developer Tools Inspector or with View➝Source
Rethink your application design. Don't try to store strings containing PHP code. Generate the string with the data you need in it in the first place.
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
$v
</body>
</html>
EOD;
echo $h;
Related
I have something like this:
PHP code at the start:
<?php
$variable="example";
?>
Then HTML code:
<html>
<head>
<title>Title</title>
</head>
<body>
Then again PHP:
<?php
// code comes here, and I want to access variable $variable here.
?>
And then HTML code ends:
</body>
</html>
Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.
Not Required unless if you are accessing it under functions ( as it will lose their scope)
test1.php
<?php
$var = 1;
//.. your code...
?>
<html>.....
<?php
echo $var; // prints 1
whereas the below code won't work...
<?php
$var = 1;
function displayVar()
{
echo $var; // You will get a notice .. !
}
Just do what you stated above and it will work.
<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>
The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.
try this
echo ($variable);
or
print($variable);
If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.
This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
Given the HTML generated by my application.
function pagination(){
echo "<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t<li>...</li>\n";
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
If I add another container DIV, this doesn't produce correctly indented code.
Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?
Amazing question.
9 answers and 3 comments so far, and looks like nobody bothered to read the question body, but just repeated some gospel triggered by a keyword in the title - a most preferred manner to answer questions on the blessed site of stackoverflow.
Yet the question not that simple/one-layered.
I have to admit, it's ambiguous itself. So, we have to dig it out.
1) How do you indent your HTML?
Use templates, dude. Use templates. The only answer.
2) Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?
Of course there isn't.
PHP knows nothing of HTML, indents and such.
Especially when no HTML is ready yet(!)
3) If I add another container DIV, this doesn't produce correctly indented code.
The key question of the question.
The question for sake of which the question were asked.
Yet hardest of them all.
And the answer is kind of ones I showed total disagreement with, hehe:
Although relative order of tags is important, for the resulting large HTML it is possible to move some blocks out of row:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<!-- news list -->
<div>
<ul>
<li>1..</li>
<li>2..</li>
<li>3..</li>
<li>4..</li>
</ul>
</div>
<!-- /news list -->
</div>
<div>
<!-- pagination -->
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
<!-- /pagination -->
</div>
</body>
</html>
It will let you have proper indention in the meaningful blocks, yet keep the main HTML in order.
As a side effect it will keep your lines on the screen :)
To keep good indentation inside sub-templates, I'd strongly suggest using PHP-based templates. Not ugly HEREDOC for goodness' sake!
Here is only one rule to follow with PHP templates:
always keep PHP blocks to the left side. That's all.
To keep indentation between PHP nested blocks, just indent them inside <? ?>
Example:
<ul>
<? foreach ($thelist as $color): ?>
<li>
<? if ($color == $current): ?>
<b><?=$color?></b>
<? else ?>
<?=$color?>
<? endif ?>
</li>
<? endforeach ?>
</ul>
This will produce correctly indented HTML, while keeping order of both HTML and PHP in the template, making developer's life easer both at development and debugging.
Do not listen to anyone who says "no need to indent your code at all!". They are merely hobbyists, not the real developers. Anyone who have an idea of what debugging is, who had hard times debugging their code, would tell you that proper indentation is essential.
The answer could sound weird, but you should not worry about the generated code's indentation. Indentation is for readability, and should be only of concern on the programmer's side, not on the generated part (which is for browsers).
I agree with all comments saying don't bother but if you do have a case where doing so makes sense then you can pipe your HTML through HTML Tidy (or in your case PHP Tidy) using the indent option.
Most editors have some sort of formatting function which can be used to fix indentation. In Visual Studio for example you can hit Ctrl + K + D to nicely format your html.
I usually do it something like this if it's a more complicated html structure. This makes it easier to follow if you ask me, and you also can write your html normally instead of worrying about escaping quotes and things like that.
Since you're not in a PHP block when it's processing the HTML, it will come out as indented as you make it.
<?php
function pagination(){
echo "</ul>\n";
for($i = 1; $i <= 10; $i++)
{
?>
<li>...</li>
<?php
}
echo "</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
You could use heredoc syntax
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
Notice all of the indenting is preserved.
EOT;
?>
If you add \t in front of ul you should be able to see the code prettied up
<?php
function pagination(){
echo "\t<ul>\n";
for($i = 1; $i <= 10; $i++)
echo "\t\t<li>...</li>\n";
echo "\t</ul>\n";
}
?>
<div>
<?php pagination(); ?>
</div>
I am a stickler for well formed code as well. Alot of people here said "firebug will indent your code for you". Well, what about when the markup delivered to the browser is modified through or injected into the DOM via javascript? Then firebug shows you the current state, not what you loaded from the server.
I also like my html to be visible and readable throughout my script. I generally do something like this, keeping track of PHP and HTML indentation separately (it is not to be able to put your cursor on an opening tag or { and just scroll the page down until you find the closing tag or } conveniently lined up with your cursors position.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div><?php
$thelist = array('Red', 'Green', 'Blue', 'Black');
echo '
<ul>';
foreach ($thelist as $color) {
echo '
<li>' . $color . '</li>';
}
echo '
</ul>';
?>
</div>
</body>
</html>
This outputs just like so,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
</div>
</body>
</html>
Notice is looks just like it should, and like it does in the script (this makes debugging simple for me). I use single quotes with HTML so I do not have to escape a trillion quotes (this makes concatenating strings a bit more manual but it is less work than all those back slashes; which also hinder readability within the script).
Once again, this is just how I do things and may not be the ideal way to handle formatting HTML. I just like to have my HTML nice and neat even when its mixed with PHP
The answer is, use templates.
If you properly separate your logic from your presentation, this question goes away. Your templates will have all the indenting or lack of indenting you want or need.
EDIT
Nonetheless, you can modify your code pretty simply:
<?php
function pagination($depth=0) {
$indent = str_pad("", $depth, "\t");
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination(1); ?>
</div>
<div>
<div>
<?php pagination(2); ?>
</div>
</div>
Alternatively, you can just pass in the indent you want:
<?php
function pagination($indent="") {
echo $indent."<ul>\n";
for($i = 1; $i <= 10; $i++)
echo $indent."\t<li>...</li>\n";
echo $indent."</ul>\n";
}
?>
<div>
<?php pagination("\t"); ?>
</div>
<div>
<div>
<?php pagination("\t\t"); ?>
</div>
</div>
Edit: broke the code down into pages.
This code really only works with a template system.
Which can just be a basic:
// file: index.tpl.html
<html>
<head>
</head>
<body>
<div>Some header code</div>
<div>
{mainContent}
</div>
<div>Some footer code</div>
</body>
</html>
// file: functions.php
<?php
function pagination()
{
$output = "<ul>\n";
for($i = 1; $i <= 10; $i++)
$output = "\t<li>...</li>\n";
$output = "</ul>\n";
return $output;
}
function indent_html($html, $tag, $new_html)
{
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{'.$tag.'}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// Uses the indent from the line above to indent your new html
return str_replace("\n", "\n".str_repeat(" ", $spacePos), $new_html);
}
?>
// file: index.php
<?php
$html = file_get_contents("index.tpl.html");
// magic indenting code: finds how many spaces are used on the line above it
$spacePos = 0;
$find = strpos($html, '{mainContent}' );
while( $html[ $find-$spacePos-1] == ' ' ) $spacePos++;
// your pagination() needs to return html not output it
$mainContent = pagination();
$mainContent = indent_html($html, $tag, $mainContent);
// Uses the indent from the line above to indent your new html
$mainContent = str_replace("\n", "\n".str_repeat(" ", $spacePos), $mainContent);
// finally insert your html
$html = str_replace("{mainContent}", $mainContent, $html);
?>
Might need some modification if you want to use tabs instead of spaces.
I use spaces as it's more cross browser/application.
Here is a very simple PHP page with one javascript function in it. I am seeing the output differently. I am not able to understand why is it behaving that way.
In the code below, x echoes as 012012, but when I pass it into a javascript function and display it in an innerHTML, it displays differently as 5130 ??!!
Can anyone help ?
<?php
$x= date("mY");
echo $x;
?>
<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body <?php echo "onload='myfunc1(".$x.")'>";?>
<div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output
012012<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body onload='myfunc1(012012)'> <div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output (screenshot)
Because a number prefixed with a 0 is treated as octal by javascript.
This is happening because 012012 is being treated as an int. But, since it starts with 0, JavaScript treats it as base 8 (octal), and therefore converts it to 5130.
You need to wrap 012012 in quotes, so JavaScript treats it as a string. Also, I suggest only using PHP to echo the value you need, not the entire function call. Makes it slightly easier to debug.
<body onload="myfunc1('<?php echo $x;?>')">
Use Smarty, is a framework template PHP!
PHP code:
<?php
$foo = date('Y');
?>
Simple Print PHP Code
<body onload="myFunctionJS('<?php echo $foo;?>')">
Simple Tags PHP(It is not recommended)
<body onload="myFunctionJS('<?=$foo;?>')">
USE SMARTY TEMPLATE FRAMEWORK
Smarty Template Framework(PHP Code):
<?php
$smarty = new Smarty;
$var = date('Y');
$smarty->assign( 'foo' , $var );
?>
Smarty Template Framework(Template Code):
<body onload="myFunctionJS('{$foo}')">
<body <?php echo "onload='myfunc1(".$x.")'>";?>
should be
<body <?php echo "onload='myfunc1(".$x.")'>";?>>
The body tag is not closed
<?php
$conn = oci_connect('usr', 'pass', 'host');
$instance_status="command1";
$spacecheck="command2";
$log_apply="command3";
$command=$_GET['name'];
echo $command;
$stid = oci_parse($conn, $command);
--some code--
?>
My HTML Page:
<html>
<title>Status Check</title>
<body>
<b>Spacecheck</b>
<b>Log Application Status</b>
<b>Database Status</b>
</body>
</html>
The above is my code, I intend to assign to $command, the value from the href variable through $_GET. But, when I test this code, $command is not being assigned the value of the variable from $_GET, rather the name of the variable is simply assigned to $command.
Eg, If I click on this:
Spacecheck
This should assign the VALUE of $spacecheck to $command, which is not happening. $command returns '$spacecheck'
How do I do this variable assignment?
You are simply writing $spacecheck. What you need to do is jump inside PHP tags and echo the variable values. Like so:
Spacecheck
or use the php echo shortcut:
Spacecheck
See the difference?
Good luck.
try going the other way around, I mean print from php:
<?php
echo '<b>Spacecheck</b>';
echo '<b>Log Application Status</b>';
echo '<b>Database Status</b>';
?>
You must use PHP open and close tags in order to place PHP code in your HTML page among other things. Try this link:
http://www.php.net/manual/en/tutorial.firstpage.php
Your HTML actually contains the literal string '$spacecheck' in the URL. $variables are only parsed in sections between tags, not in plain HTML.
Try this in your HTML file (which should be called .php) instead:
<?php
$spacecheck = 'foobar'; // (some dummy values)
$log_apply = 'nope';
$instance_status = 'idle';
print("<html>
<title>Status Check</title>
<body>
<b><a href='oraData.php?name=$spacecheck'>Spacecheck</a></b>
<b><a href='oraData.php?name=$log_apply'>Log Application Status</a></b>
<b><a href='oraData.php?name=$instance_status'>Database Status</a></b>
</body>
</html>");
?>
I have a file called: file.php
contained in this file is the following code:
<script type="text/javascript">
//....
var sumJS = 10;
<?php $sumPHP = sumJS ?>
</script>
<?php echo "Sum = " . $sumPHP ?>
How can I assign sumJS for $sumPHP?
If I would like to make this conversely then I would write:
$sumPHP = 10;
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
But how can I re-make this for my problem?
Javascript can change the variables of PHP and vice versa.
Here is an example of that.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php $aphp=1 ?>
<script "text/javascript">document.write("<?php $aphp=2 ?>")
var ajava=1;</script>
<?php echo "aphp= $aphp"; echo "<br>";
echo "<script \"text/javascript\">ajava=2;</script>"
?>
<script "text/javascript">document.write("ajava= "); document.write(ajava)</script>
</body>
</html>
What if I want to assign a php variable to a java variable and vice versa
The above showed that you can assign values to java in php and vice versa by simply writing out an assignment using echo in php and document.write in java. That is how you assign a value.
Mixing actual variables between php and java is not much more complicated. What you do is write an assignment in the language you need to get the value of a variable from and assign it to a variable in the other language. Here is an example of that.
Assign php to java
<?php echo "<script type='text/javascript'>javasum=$phpsum</script>" ?>
assign java to php can be done in two ways
<script type='text/javascript'>var str="<?php $phpsum=";
str=str+javasum; str=str+" ?>";
document.write(str);
</script>
or more conveniently
javasum=<?php echo $phpsum ?>;
Mixing php and javascript to do things other than variable assignments
Javascript can also be mixed in the phpcode to do a javascript function in the phpcode. Say you wanted to use javascript to highlight text only if a condition is met in the php code. But to do this you need to echo the javascript code section. Also use the escape character, \' to include quotes in a echo command. Here is an example of this
Before you get started be sure php content type is in html. In dreamweaver site editor software, a header to do this is automatically included.
<p><span id="htext">htext</span></p>
<?php
$a=5;
echo "<h3> hello world</h3>";
if ($a==5) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById(\"htext\").style=\"background-color:yellow\"";
echo "</script>";
}
?>
<p>is a=5</p>
<p><?php echo $a ?> </p>
$sumPHP is a server-side value, which will be evaluated on the server. Then the server generates page content and sent it to the client. Then browsers receive the page content and evaluate client-side value sumJS.
So you can never assign sumJS for $sumPHP because $sumPHP is calculated before sumJS.
But can do this to show the page:
<?php echo "Sum = "?><script type="text/javascript">document.write(sumJS);</script>
or rather
<script type="text/javascript">document.write('Sum = ' + sumJS);</script>
You're just missing tags
<?php
$sumPHP = 10;
?>
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
demo
Sorry that at the moment I do not have the time to write an example. But I believe that this idea will work. Maybe someone here can do a quick test.
Just create a hidden element with a unique id, say a
span with id="uniqueBufferForCommunicatingBetweenPHPandJS" and style="display:none".
Then, with the JS part of the code, write the result into this span by using
document.getElementById("uniqueBufferForCommunicationBetweenPHPandJS").innerHTML = XXX;
You can even write XXX in the form of JSON.
Afterwards, you can use something in PHP like
$bufferspan = $dom->getElementById('uniqueBufferForCommunicationBetweenPHPandJS');
to get the span, and read its content, probably by using
$avariable = $dom->ownerDocument->saveHTML($avariable);
and then interpret the result stored in $avariable. I am not totally sure about the last PHP code.