简体   繁体   中英

Use PHP to dump mysql values into JSON file

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);
?> 

This will create the file.json file but the file only contains "null".

Try something like this.

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);

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.

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.

So either:

// 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);

...

Most likely to be UTF-8 problem with special characters, try this

<?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);
?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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