繁体   English   中英

使用PHP将mysql值转储到JSON文件中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM