문제

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>.

도움이 되었습니까?

해결책

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.

다른 팁

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>

You will have to echo the variable like this:

  <?php echo $data; ?>

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; ?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top