Difference meta and PHP header

2019-08-08 21:39发布

问题:

What is the difference between these two and should I use both ? I want my website to be fully UTF-8.

In PHP:

<?php 
header("Content-Type: text/html; charset=utf-8");
?>

And the meta tag in HTML:

<meta charset="utf-8">

回答1:

The HTTP Content-Type header should always be set, it's the primary source for the browser to figure out what kind of document it's dealing with. Only if this header is missing will the browser try to find an HTML meta tag which gives it the same information as a fallback.

It makes sense to set both flags though, since you may save the HTML document to disk, in which case the HTTP header will be gone for anyone needing it later.

You can find the exact rules for how a browser determines the document's charset here: http://www.w3.org/TR/html5/syntax.html#determining-the-character-encoding



回答2:

header("Content-Type: text/html; charset=utf-8");

is server side and depends upon the PHP script calling it before it will send the new page to the client.

<meta charset="utf-8">

The meta element has two uses: either to emulate the use of an HTTP response header, or to embed additional metadata within the HTML document. So the Meta Tag is the best way to have utf-8 on your site.