Writing PHP in <head>

夙愿已清 提交于 2019-12-13 16:24:13

问题


Is it valid to store PHP variables/values inside the <head> tag? Are there any disadvantages or advantages to writing PHP with HTML in this format? Does it even matter?

I sampled the following code as direct input through the W3C Validator:

<!DOCTYPE html> 
<html>
<head>
  <title>PHP Head Test</title>
  <?php $data; ?>
</head>
</html>

And I get 1 error:

Line 5, Column 4: Saw <?. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)
<?php $data; ?>

But I'm guessing that's because it's validating an .html file that has php code in it.

I am planning to use PHP to store preprocessed MySQL data into a variable to use in Javascript. Is the <head> the proper place to store these values?

NOTE: I am not trying to print out data in the head, that would be silly. I am asking about storing preprocessed data from MySQL to PHP (to be used in Javascript) in the <head>.


回答1:


No, storing PHP variables in the head is not the proper way to do it. In fact, when you do this, your variables are NOT stored inside the head, PHP is server side, HTML/CSS/Javascript are client side.

You want to store your variables before there is even any HTML that is outputted.

However, if you do something like this :

<head>
    <title>PHP Head Test</title>
    <?php $data; ?>
</head>

It's not actually doing anything, if you wanted to display it, you would use echo. This code does absolutely nothing except declare $data if it wasn't declared before-hand.

Generally, you should have most of your PHP code out of your HTML file, they should be in completely different files and the PHP code should include the HTML file. In this case, the PHP code that you put in the HTML file will have access to all PHP variables that were available in the file where it was included.




回答2:


I am planning to use PHP to store preprocessed MySQL data into a variable to use in Javascript. Is the the proper place to store these values?

just do something like that;

<script>
    function Myfunction() {
        var myVariableGeneratedByPhp = <?php echo $data; ?>;
        // use your variable here
    }
</script>



回答3:


You will have to echo the variable like this:

  <?php echo $data; ?>



回答4:


It is valid to use it but not for a big script. It will be complicated to debug after that. beIt can be use if you want to generate a dynamic tag for example, you will need it.

But you only can print data so change:

<?php $data; ?>

should be :

<?php echo $data; ?>


来源:https://stackoverflow.com/questions/17710674/writing-php-in-head

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!