0

I want to save a mySQL-query in a json file with php. To get data from the query result I do

$resArray = array();
    while($row = mysqli_fetch_assoc($result)) {
        $resArray[] = $row;
    }

    echo json_encode($resArray);

Some fields may contain 'ä', 'ö' and 'ü'. For example I have "category":"Stöcke". When json_encode the result array, fields with ä, ö and ü will be encoded as null, e.g. "category":null How to correctly encode all resultsets to save the json correct and show all fields and contents?

Dennis Konoppa
  • 189
  • 1
  • 3
  • 13

2 Answers2

1

Okay. with all answers from you I created the solution! Thanks to everyone, I'm combining utf8_encode for every row field with JSON_UNESCAPED_UNICODE for json_encode:

// get result from query
        $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

        // get infos for all columns
        $columnInfos = mysqli_fetch_fields($result);


        // create an array
        $resArray = array();
        while($row = mysqli_fetch_assoc($result)) {
            foreach ($columnInfos as $info) {
                $row[$info->name] = utf8_encode($row[$info->name]);
            }
            $resArray[] = $row;
        }

        echo json_encode($resArray, JSON_UNESCAPED_UNICODE);
Dennis Konoppa
  • 189
  • 1
  • 3
  • 13
0

json_encode() only supports UTF-8 encoding. Read this.

So either you switch the project to UTF-8 or you make sure you utf8_encode() any string before using json_encode().

Brane
  • 3,257
  • 2
  • 42
  • 53