1

For a school project I have to display database data as a valid json file.

            $result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");

            echo "{ \"films\" : [";
            while ($row = mysqli_fetch_array($result)) {
                $jsonResult = json_encode($row);
                echo $jsonResult;
                echo ",";   
            }
                echo "]}";

The output i get is:

{
    "films": [
        {
            "0": "Man on fire",
            "titel": "Man on fire",
            "1": "Actie",
            "genre": "Actie"
        },
        {
            "0": "Dumb and Dumberer",
            "titel": "Dumb and Dumberer",
            "1": "Comedy",
            "genre": "Comedy"
        },
        {
            "0": "DefQon 2014",
            "titel": "DefQon 2014",
            "1": "Muziek",
            "genre": "Muziek"
        },

    ]
}

Now my question is, how do I remove the last comma, I cannot find that. And all data tells the data 2 times, I also don't know how to avoid this.

3
  • AFAIK, the trailing comma in JSON arrays is ok, you should not care about it. Commented Jan 11, 2015 at 18:37
  • 1
    Collect the entire result in one PHP array, and then json_encode it all at once after it's built. Commented Jan 11, 2015 at 18:40
  • 1
    @Necto No, it's not OK. It is invalid and most libraries will fail on it - including PHP's json_decode. Commented Jan 11, 2015 at 18:42

2 Answers 2

2

Let json_encode handle the entire thing - build one array of data, and use json_encode on that.

$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");

$response = array();
$response['films'] = array();

while ($row = mysqli_fetch_array($result)) {
  $response['films'][] = $row;
}

echo json_encode($response);
Sign up to request clarification or add additional context in comments.

2 Comments

Great, this helped!:) Now i just have the double data in, i don't know where it comes from. It is not in my database.. the "0" data and the "1" data
@Patrick Use mysqli_fetch_assoc instead of mysqli_fetch_array to fix that or do mysqli_fetch_array($result, MYSQLI_ASSOC). The default behaviour is MYSQLI_BOTH which spits out both an associative and a numeric array.
0

A good way to do this, is to not place a comma after writing every record, but instead before every record.

Then all you have to do, is add an if statement that doesn't output the comma for the very first row.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.