I want to encode an object using JSON to answer an AJAX request. First, I convert the object to an array (the result of this looks okey), then I use json_encode
to encode the array to the JSON format, but I get an unexpected result. The obtained JSON string has the class name before the property names and the null character 000 appears in many places. All of my files are encoded using UTF-8. If I use get_object_vars
, the I get the result array = []
.
我如何解决这一问题?
同上。
The Code I used:
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);