为什么PHP头文件(字符集)工作,而HTML <meta charset =“”/>没有?

时间:2016-09-21 13:55:30

标签: php html character-encoding

这个可能很容易,但对我的服务器(或我自己)来说似乎是一个问题。

我在index.php中有这段代码:

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

// Some code for generating data to be displayed
foreach ($ObjectArray as $SingleObject) {
        print_r($SingleObject->getAllProperties());
    }

这样做:

Expected result, achievable with header()

但我不想使用header('Content-Type: text/plain; charset="UTF-8"'); - 我宁愿包含header.htm的HTML代码:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Test Cards</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="jquery-3.1.0.min.js"></script>
        <link rel="stylesheet" href="jquery-ui.css">
        <script src="jquery-ui.js"></script>
    </head>

我的index.php就是这样:

<?php
include 'view/header.htm';
echo '<body>';
// Some code for generating data to be displayed
foreach ($ObjectArray as $SingleObject) {
        print_r($SingleObject->getAllProperties());
echo '</body>';
echo '</html>';
}

不幸的是,这太好了。 Charset仍然被认为是UTF-8,但结果远非我的期望:

Unexpected result, when normal HTML is used

请告诉我,发生了什么以及如何处理这类问题。是组合HTML和PHP的情况(干净的PHP确实在HTML出现时使用了一些奇特的样式吗?)或者我的代码中可能有些错误?

提前致谢:)

1 个答案:

答案 0 :(得分:1)

保留格式化的外观,因为在第一种情况下,您具有内容类型text/plain,而在第二种情况下,它是HTML(text/html)。 您可以将其包装在<pre></pre>标记中,以便在返回HTML时保留格式。

<?php

include 'view/header.php';
echo '<body>';
echo '<pre>';
// ...
// your foreach here
// ...
echo '</pre>';
echo '</body>';
相关问题