Reputation: 1
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 '\0000' 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 = []
.
How I can resolve this issue?
I got result: {"\u0000DB\u0000connection":null,"\u0000DB\u0000serverName":"localhost","\u0000DB\u0000userName":"root","\u0000DB\u0000password":null,"\u0000DB\u0000dbName":"thahtin"}
Here is 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);
Upvotes: 0
Views: 139
Reputation: 128991
get_object_vars
returns an empty array because all of your properties are private. Make them public, or (better), construct the array yourself so you can control what's in it.
Upvotes: 3