Do I need a !DOCTYPE declaration in a php file with html?

前端 未结 10 1102
面向向阳花
面向向阳花 2020-12-15 03:16

I have a php file with my website content in it. The file needs to be .php because i get some variables first and then use it later in the website content. Like this example

相关标签:
10条回答
  • 2020-12-15 03:28

    When they contain embedded HTML, it's better to think of .php files as regular HTML files which the server has been instructed to scan for dynamic (PHP) code.

    A valid !DOCTYPE declaration is still necessary for the document to be semantic.

    0 讨论(0)
  • 2020-12-15 03:35

    Your final output is HTML which is what uses the doctype. So, yes, you need one. If it is breaking your CSS then your HTML and/or CSS is wrong and needs to be fixed.

    0 讨论(0)
  • 2020-12-15 03:37

    As others have said, !DOCTYPE is necessary in php scripts that are outputting HTML. If you were creating an image or executing a bash file or something, the story would be different.

    As for where it belongs, it's a good idea to put it at the start just so you don't accidentally output something before it, but if you are using session variables or sending headers, you will want to make sure to do those things BEFORE declaring a doctype. Remember, there can be NO browser output (even whitespace) before headers are sent through php or sessions are started.

    0 讨论(0)
  • 2020-12-15 03:39

    Yes you need a DOCTYPE as your browser only sees the following part of the above code

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Page Title</title>
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>
    Welcome THE USER NAME
    </body>
    </html>
    

    I usually place the close PHP tag and the DOCTYPE together like so ?><!DOCTYPE HTML>

    0 讨论(0)
  • 2020-12-15 03:43

    PHP really has nothing to do with HTML - it's just the server-side code spitting out a bunch of text that the browser interprets.

    A doctype is a critical part of how the browser interprets the HTML that follows.

    0 讨论(0)
  • 2020-12-15 03:46

    Sorry to resurrect the dead, but no one seems to explain why you need a doctype in HTML (yes a PHP script outputting HTML is an HTML file at the end).

    Declaring a doctype affects the way the browser interprets your HTML (this is probably why your css code may stop working without a doctype). Basically there's 2 ways: quirks mode and strict mode. The latter is sticking to standards, so you should always tell the browser which HTML standard your code is following (nowadays you probably want HTML5 which has the simplest doctype: <!DOCTYPE html>).

    See here for a more detailed explanation.

    0 讨论(0)
提交回复
热议问题