我想使用JSON对对象进行编码来回答AJAX请求。首先,我将对象转换为数组(结果看起来像okey),然后我使用json_encode
将数组编码为JSON格式,但是我得到了意想不到的结果。获取的JSON字符串在属性名称前面具有类名称,并且在许多位置出现空字符“\ 0000”。我的所有文件都使用UTF-8编码。如果我使用get_object_vars
,我会得到结果array = []
。
我如何解决这个问题?
我得到了结果:{"\u0000DB\u0000connection":null,"\u0000DB\u0000serverName":"localhost","\u0000DB\u0000userName":"root","\u0000DB\u0000password":null,"\u0000DB\u0000dbName":"thahtin"}
以下是我使用的代码:
class DB
{
private $connection;
private $serverName;
private $userName;
private $password;
private $dbName;
public function __construct()
{
$config = new Configuration();
$this->serverName = 'localhost'; //$config->getConfig("server");
$this->userName = 'root'; //$config->getConfig("userName");
$this->password = null; //$config->getConfig("password");
$this->dbName = 'thahtin'; //$config->getConfig("database");
}
public function open()
{
if(!$this->connection)
mysql_close($this->connection);
$this->connection = mysql_connect($this->serverName, $this->userName, $this->password);
if(!$this->connection)
{
die('Could not connect. Error: ' . mysql_error());
}
mysql_select_db($dbName);
}
}
$db = new DB();
echo json_encode((array)$db);