[英]Use PHP to dump mysql values into JSON file
我正在嘗試通過使用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”。
嘗試這樣的事情。
error_reporting(-1);
$result = mysql_query("SELECT * FROM wp_posts");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['posts']['post_status'][] = $row['post_status'];
$data['posts']['post_title'][] = $row['post_title'];
}
$json_string = json_encode($data);
$file = 'file.json';
file_put_contents($file, $json_string);
隨機猜測: json_encode
期望使用UTF-8編碼的數據,並且會表現出您在任何非UTF-8,非ASCII輸入上描述的行為。 您從數據庫中獲取的數據可能是Latin-1編碼的。
將您的數據庫連接設置為utf8
以直接從數據庫中接收UTF-8編碼的數據(請參閱完整的UTF-8 ),或者使用(我討厭這樣說,因為此功能經常被濫用,甚至不好笑) ,但此處正確應用) utf8_encode
將從數據庫中獲取的所有數據轉換為Latin-1到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);
...
最有可能是特殊字符的UTF-8問題,請嘗試此操作
<?php
error_reporting(-1);
$result = mysql_query("SELECT * FROM wp_posts");
$i = 0;
while ($row = mysql_fetch_array($result)) {
$response[$i]['post_status'] = htmlentities($row['post_status'],ENT_COMPAT, 'ISO-8859-1');
$response[$i]['post_title'] = htmlentities($row['post_title'],ENT_COMPAT, 'ISO-8859-1');
$data['posts'][$i] = $response[$i];
$i = $i + 1;
}
$json_string = json_encode($data);
$file = 'file.json';
file_put_contents($file, $json_string);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.