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);
5.4 용으로 개발하지는 않지만 [JsonSerializable] (http://www.php.net/manual/en/class.jsonserializable.php)을 살펴보십시오. – Dan