0

What I am trying to achieve is to simply put all the rows of a mysqli result to a JSON file.

My code looks like this:

$sth = mysqli_query($mysqli, "SELECT * FROM table");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print_r($rows);
$mysqli->close();
$fileobj = fopen("takeOutItems.json", 'w');
fwrite($fileobj,json_encode($rows));
fclose($fileobj);

printing the $rows arrays shows data correctly. fwrite, however, does not change anything in takeOutItems.json.

What am I doing wrong?

10
  • 1
    does print_r print in the browser with that data? Commented Nov 12, 2021 at 9:24
  • 2
    have you tried file_put_contents('takeOutItems.json',json_encode($rows)); ? Commented Nov 12, 2021 at 9:27
  • 1
    if it's does not working you'll need to check the directory permission. Commented Nov 12, 2021 at 9:28
  • 1
    Can you try to print the json_encode using echo?, will see if the array is parse into json successfully. Commented Nov 12, 2021 at 9:30
  • 3
    You may see this, I think the possible problem is the encoding stackoverflow.com/questions/19361282/… Commented Nov 12, 2021 at 9:35

1 Answer 1

2

The issue was that some data elements were not displayed correctly. Adding $mysqli->set_charset("utf8"); resolved the issue.

Sign up to request clarification or add additional context in comments.

2 Comments

good work, although you can convert it on utf8 using utf8encode function
Please stop using the deprecated utf8 charset. Use utf8mb4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.