我是 PHP、HTML 和 MySQL 新手,遇到了以下问题:
我有一个 PHP 文档,它输出 MySQL 查询的结果。由于MySQL数据库以及输出结果有一些非标准字符(例如æ或á),因此我的PHP文档和MySQL数据库/表都编码为utf-8。
例如,以下是数据库条目和正确输出的示例:
goahteæjgáda
当PHP文档的HTML中没有任何内容时<head/>
节点(甚至没有注释),则搜索成功并且输出显示正确(但随后我无法应用外部 css 或包含快捷方式图标等)。
但是,如果 HTML <head/>
中有任何内容节点,例如有关内容类型的标准元数据、CSS 和图标文件的链接、关键字,甚至只是 <!-- comments -->
,然后:
- 如果搜索的字符串包含非标准字符,则搜索不起作用
或 - 结果输出中的任何非标准字符都显示为 � - 例如,上面的示例在搜索“goahte”后显示如下:
goahte�jg�da
如有任何帮助,我们将不胜感激!
这是我的代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href='style_mavsulasj.css' rel='stylesheet' type='text/css'/>
<link rel='shortcut icon' href='farben4.gif'/>
<title>search</title>
</head>
<body>
<div style="width:230px;padding:0px;margin:0px;float:left;">
<table border="0">
<tr><td>Search here:</td><td>
<?php if (strlen($_GET['smj'])==0) echo ""; else echo "current search"; ?>
</td></tr>
<form action="" method="GET">
<tr><td colspan="2">Entry:</td></tr>
<tr><td><input type='text' name='smj' value=''></input></td><td align='center'><?php echo "<span class='searchCrits' > ".$_GET['smj']."</span>"; ?></td></tr>
<tr><td colspan="2"><input type="submit" value="submit query"/></td></tr>
</form>
</table>
</div>
<div style="width:960px;padding:30px;margin-left:210px;">
<?php
if($_GET){
$smj = $_GET['smj'];
$connect = mysql_connect("localhost","root","root");
if($connect){
$toDB = mysql_select_db("bigG_reimport_test",$connect);
if($toDB){
$query = "SELECT * FROM reimport_Sheet1 WHERE smj LIKE '" . $smj . "%'";
$results = mysql_query($query);
echo "<span class='header4'>results:<br/>";
while($row = mysql_fetch_array($results)){
echo "-> " . $row['smj'] . "<br/>" ;
}
echo "</span><br/>";
}
else {die("Failed to connect to database!<br/>" . mysql_error());}}
else {die("Failed to connect to mysql!<br/>" . mysql_error());}}
?>
</div>
</body>
</html>
最佳答案
确保:
- 您的 PHP 源文件被编码为 UTF-8(是的,遗憾的是,这确实很重要)
- 您已将 MySQL session 中的字符集设置为 UTF-8。请参阅mysql_set_charset
- 您在 HTTP header 中将编码设置为 UTF-8。
关于php - 编码冲突: php output corrupted by html <head> content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9168230/