Mysqli数据到文件转换

时间:2018-03-06 21:03:10

标签: php json

我在项目中从数据库中获取数据(当前只有一行)并将其写入文件

中获得以下代码
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
mysqli_set_charset($conn,"utf8");
$sqlTot = $sqlRec = "";
$sql = "SELECT * FROM `prisoners` ";
$sqlTot .= $sql;
$sqlRec .= $sql;

$sqlRec .=  " ORDER BY id";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch prisoner data");

$data = array();
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) { 
    $data[] = $row;
}   

file_put_contents("data.txt", print_r($data, true));
?>

但是,这会将特定行写成如下

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Παπαευθυμίου (ή Παπαδόπουλος)
            [2] => Χαράλαμπος
        )
)

虽然我希望它输出像

{
  "data": [
    {
      "id": "1",
      "lastname": "Παπαευθυμίου (ή Παπαδόπουλος)",
      "firstname": "Χαράλαμπος"
    }
  ]
}

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

您可以使用mysqli_fetch_assoc()获取关联数组以获取列名。

然后使用json_encode()根据需要显示:

$data = array();
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_assoc($queryRecords) ) { 
    $data['data'][] = $row;
}
file_put_contents("data.txt", json_encode($data, JSON_PRETTY_PRINT));

编辑,如下面的评论中所示(对于希腊语(unicode)字符):

file_put_contents("data.txt", json_encode($data, 
       JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));

答案 1 :(得分:-1)

您可以使用json_encode()方法来实现此目的:

file_put_contents("data.txt", json_encode($data));