我正在尝试使用 PHP 从 mysql 数据库生成 JSON 文件。到目前为止,我有:
<?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”。
随机猜测:json_encode
需要 UTF-8 编码数据,并将在任何非 UTF-8、非 ASCII 输入上表现出您所描述的行为。您从数据库获取的数据可能是 Latin-1 编码的。
Either set your database connection to utf8
to receive UTF-8 encoded data directly from the database (see UTF-8 all the way through https://stackoverflow.com/q/279170/476), 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 http://php.net/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);
...
or:
$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);
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)