b3253223b33v
b3253223b33v

Reputation: 27

Write JSON file from MySql using php

I want to add Data before the array and it is written into the converted json. I have checked that there are no errors when converting, but why isn't there?

This the code

$response = array();
while($row =mysqli_fetch_assoc($result))
{
    $response[] = $row;
}
echo json_encode($response);
    //write to json file
$fp = fopen('op.json', 'w');
fwrite($fp, json_encode('{"Data":', $response), '}');// JSON_PRETTY_PRINT
fclose($fp);

Previous results like this

[
  {
    "id": "6",
    "name": "kiko",
    "score": "999"
  },
  {
    "id": "9",
    "name": "johyn",
    "score": "88"
  },
  {
    "id": "12",
    "name": "aaaani",
    "score": "99"
  }
]

I want the results like this

{
  "Data": [
    {
      "id": "6",
      "name": "kiko",
      "score": "999"
    },
    {
      "id": "9",
      "name": "johyn",
      "score": "88"
    },
    {
      "id": "12",
      "name": "aaaani",
      "score": "99"
    }
  ]
}

Upvotes: 0

Views: 279

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94662

json_encode() encodes an array or object to a JSON String, so make the parameter an array and it will work

fwrite($fp, json_encode(["Data" => $response]);

Or to get JSON_PRETTY_PRINT

fwrite($fp, json_encode(["Data" => $response], JSON_PRETTY_PRINT);

Upvotes: 2

War10ck
War10ck

Reputation: 12508

Rather than trying to code the JSON and then json_encode() it you can use an array to generate the desired output:

$response = array();
while($row =mysqli_fetch_assoc($result))
{
    $response[] = $row;
}
echo json_encode($response);
    //write to json file
$fp = fopen('op.json', 'w');
fwrite($fp, json_encode(array('Data' => $response), JSON_PRETTY_PRINT)); // JSON_PRETTY_PRINT
fclose($fp);

In addition, json_encode() has the ability to pretty print the json by supplying the second parameter.

Upvotes: 1

Related Questions