2012-04-20 86 views
0

我想使用JSON對對象進行編碼以回答AJAX請求。首先,我將對象轉換爲數組(這看起來像是okey的結果),然後我使用json_encode將數組編碼爲JSON格式,但我得到了意想不到的結果。所獲得的JSON字符串在屬性名稱前有類名,在許多地方出現空字符'\ 0000'。我所有的文件都使用UTF-8編碼。如果我使用get_object_vars,我得到結果array = []json_encode給出了意想不到的結果

我該如何解決這個問題?

我得到的結果:{"\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); 
+0

不太可能你正在爲5.4開發,但看看[JsonSerializable](http://www.php.net/manual/en/class.jsonserializable.php)。 – Dan 2012-04-20 04:34:41

回答

3

get_object_vars返回一個空數組,因爲所有的屬性都是私有的。讓他們公開,或者(更好),自己構建陣列,以便控制其中的內容。

相關問題