PHP网页乱码通常是由于字符编码不一致导致的。字符编码是指计算机如何表示和存储文本数据的方式。常见的字符编码有ASCII、UTF-8、GBK等。
确保PHP文件本身使用UTF-8编码保存。
<?php
header('Content-Type: text/html; charset=utf-8');
?>
确保数据库连接时指定正确的编码。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 设置数据库编码
$conn->set_charset("utf8");
// 执行查询
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
确保HTTP响应头中指定的编码与实际内容编码一致。
<?php
header('Content-Type: text/html; charset=utf-8');
?>
通过以上方法,可以有效解决PHP网页乱码的问题。如果问题依然存在,建议检查其他可能影响编码的因素,如浏览器设置、操作系统默认编码等。
领取专属 10元无门槛券
手把手带您无忧上云