我有一个utf8-unicode格式的数据库。 我想做的就是将数据从MySQL更改为json格式。
这是我的代码。
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "book");
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('book', $connection);
mysql_query("SET NAMES 'utf8'", $connection);
if(mysqli_connect_errno()){
die( "Database connection failed" .
mysqli_connect_error().
"(" . mysqli_connect_errno() . ")"
);
}
$query = sprintf("SELECT * FROM list");
$result = mysql_query($query,$connection);
$num_rows = mysql_num_rows($result);
$out = "{\"books\":";
$out .= "[";
while($toshow = mysql_fetch_assoc($result)){
$Id = $toshow['id'];
$BookName = $toshow['book_name'];
$Author = $toshow['author'];
$AuthorOrder = $toshow['author_order'];
$Cat = $toshow['cat'];
$out .= "{";
$out .= "\"Book Name\" : \" " . $BookName . "\",";
$out .= "\"Author\" : \" " . $Author . "\",";
$out = rtrim($out,",");
$out .= "},";
}
$result = rtrim($out,",");
$result .= "]}";
echo ($result);
mysql_close($connection);
?>
但是输出没有以正确的字符编码显示。 有任何建议要获得正确的json输出吗?
答案 0 :(得分:0)
您可以将 array_push 与 json_encode
一起使用<?php
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "book");
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('book', $connection);
mysql_query("SET NAMES 'utf8'", $connection);
if(mysqli_connect_errno()){
die( "Database connection failed" .
mysqli_connect_error().
"(" . mysqli_connect_errno() . ")"
);
}
$books = array();
$query = sprintf("SELECT * FROM list");
$result = mysql_query($query,$connection);
$num_rows = mysql_num_rows($result);
while($toshow = mysql_fetch_assoc($result)){
$Id = $toshow['id'];
$BookName = $toshow['book_name'];
$Author = $toshow['author'];
$AuthorOrder = $toshow['author_order'];
$Cat = $toshow['cat'];
array_push($books,
array(
"Id" => $Id,
"Book Name" => $BookName,
"Author" => $Author
)
);
}
$out = json_encode($books);
echo $out;