Krzysztof Krzysztof - 2 months ago 4
HTML Question

Why does PHP header(charset) work while HTML <meta charset> doesn't?

this one may be easy, but seems a problem for my server (or me myself).

I have this piece of code in

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());
}


And it does this:

Expected result, achievable with header()

But I don't want to use
header('Content-Type: text/plain; charset="UTF-8"');
- I'd rather include HTML code from my
header.htm
:

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


with my
index.php
like that:

<?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>';
}


Unfortunately, this ain't too good. Charset still is recognized as UTF-8, but the result is far from my expectations:

Unexpected result, when normal HTML is used

Please tell me, what is happening and how to handle this kind of problem. Is it a case of combining HTML and PHP (clean PHP does use some fancy styling when HTML ain't present?) or maybe some mistake in my code?

Thanks in advance :)

Answer

The formatted look is preserved, because in the first case you have the content-type text/plain, while in the second case it is HTML (text/html). You can wrap it in <pre></pre> tags to preserve formatting when returning HTML.

<?php

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