我有一组关键字通过 JSON 从数据库(编码的 UTF-8)传递,其中一些可能具有特殊字符,如 é、è、ç 等。这用作自动完成器的一部分。例子:
array('Coffee', 'Cappuccino', 'Café');
我应该补充一点,来自数据库的数组将是:
array('Coffee', 'Cappuccino', 'Café');
但 JSON 编码为:
["coffee", "cappuccino", null];
如果我通过 print_r() 打印这些内容,它们在 UTF-8 编码的网页上显示得很好,但如果我想使用 print_r($array) 查看数组,如果使用 text/plain,café 会显示为“café” ;出口();。
如果我在编码为 JSON 之前使用 utf8_encode() 进行编码,则效果很好,但网页上打印的内容是“café”而不是“café”。
同样奇怪的是, json_last_error() 被视为未定义的函数,但 json_decode() 和 json_encode() 工作正常。
关于如何从数据库获取 UTF-8 编码数据并在整个过程中表现相同的任何想法?
EIDT:这是获取关键字并将它们放入单个数组的 PHP 函数:
private function get_keywords()
{
global $db, $json;
$output = array();
$db->query("SELECT keywords FROM listings");
while ($r = $db->get_array())
{
$split = explode(",", $r['keywords']);
foreach ($split as $s)
{
$s = trim($s);
if ($s != "" && !in_array($s, $output)) $output[] = strtolower($s);
}
}
$json->echo_json($output);
}
json::echo_json 方法只是编码、设置标头并打印它(用于 Prototype)
编辑:数据库连接方法:
function connect()
{
if ($this->set['sql_connect'])
{
$this->connection = @mysql_connect( $this->set['sql_host'], $this->set['sql_user'], $this->set['sql_pass'])
OR $this->debug( "Connection Error", mysql_errno() .": ". mysql_error());
$this->db = @mysql_select_db( $this->set['sql_name'], $this->connection)
OR $this->debug( "Database Error", "Cannot Select Database '". $this->set['sql_name'] ."'");
$this->is_connected = TRUE;
}
return TRUE;
}
更多更新:
我运行的简单 PHP 脚本:
echo json_encode( array("Café") ); // ["Caf\u00e9"]
echo json_encode( array("Café") ); // null