使用PHP将mysql值转储到JSON文件中
我正在尝试使用PHP从mysql数据库生成JSON文件.到目前为止,我有:
I am trying to generate a JSON file from a mysql database by using PHP. So far, I have:
<?php
error_reporting(-1);
$result=mysql_query("SELECT * FROM wp_posts");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['post_status'] = $row['post_status'];
$response[$i]['post_title']= $row['post_title'];
$data['posts'][$i] = $response[$i];
$i=$i+1;
}
$json_string = json_encode($data);
$file = 'file.json';
file_put_contents($file, $json_string);
?>
这将创建file.json文件,但该文件仅包含"null".
This will create the file.json file but the file only contains "null".
随机猜测:json_encode
期望使用UTF-8编码的数据,并且将表现出您在任何非UTF-8,非ASCII输入上描述的行为.您从数据库中获取的数据可能是Latin-1编码的.
Random guess: json_encode
expects UTF-8 encoded data and will exhibit the behavior you describe on any non-UTF-8, non-ASCII input. The data you're getting from the database is likely Latin-1 encoded.
将数据库连接设置为utf8
,以直接从数据库接收UTF-8编码的数据(请参见所有)或使用(我讨厌这样说,因为此功能经常被滥用,甚至不有趣,但在此处已正确应用)
Either set your database connection to utf8
to receive UTF-8 encoded data directly from the database (see UTF-8 all the way through), or use (and I hate to say this, because this function is so often abused it's not even funny, but it's correctly applied here)utf8_encode
on all data you get from the database to convert it from Latin-1 to UTF-8.
所以:
// set the connection charset
mysql_set_charset('utf8');
$result = mysql_query("SELECT post_status, post_title FROM wp_posts");
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data['posts'][] = $row;
}
$json_string = json_encode($data);
...
或:
$result = mysql_query("SELECT post_status, post_title FROM wp_posts");
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$row = array_map('utf8_encode', $row);
$data['posts'][] = $row;
}
$json_string = json_encode($data);
...