0

JSON encoding unsuccessful when data consists umlauts (e.g: ä, ö, ü, õ) and when I replace these letters or remove manually from my MySQL table, everything works perfectly.

It does not give me any errors but JSON is just not appearing.

I really need a fix for my problem because every letter counts. Especially when it is about names.

<?php

Header('Content-Type: application/json; charset=UTF-8');

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App;

$app->get('/api/standings', function(Request $request, Response $response){
    $sql = "SELECT * FROM standings";

    try {
        $db = new db();
        $db = $db->connect();

        $stmt = $db->query($sql);
        $standings = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;

        $json = json_encode($standings, JSON_UNESCAPED_UNICODE);
        echo $json;

    } catch(PDOException $e) {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }
});
  • Add `$error = json_last_error(); var_dump($json, $error === JSON_ERROR_UTF8);` below json_encode to find out if the UTF8 encoding is correct or not – Raymond Nijland Feb 18 '17 at 17:05
  • try a print_r on the $standings array and post the data so we can simulate your issue. – MikeSchem Feb 18 '17 at 17:38
  • @RaymondNijland After adding `$error = json_last_error(); var_dump($json, $error === JSON_ERROR_UTF8);` this was printed out: `bool(false) bool(true)` –  Feb 20 '17 at 21:44
  • @MikeSchem after adding `print_r($standings);` this was printed out: `Array ( [0] => stdClass Object ( [id] => 1 [position] => 1. [teamName] => Tartu �likool [teamWins] => 22W [teamLosses] => 2L ) [1] => stdClass Object ( [id] => 2 [position] => 2. [teamName] => BC Kalev/Cramo [teamWins] => 24W [teamLosses] => 3L ) [2] => stdClass Object ( [id] => 3 [position] => 3. [teamName] => AVIS Rapla [teamWins] => 14W [teamLosses] => 7L ) [3] => stdClass Object ( [id] => 4 [position] => 4. [teamName] => TT� KK [teamWins] => 11W [teamLosses] => 8L ) [4] => stdClass Object etc...` –  Feb 20 '17 at 21:49
  • Show us also the code off the db class i think we need it to fix the database connection encoding.. edit the question to insert the code... i think you need to do something like this http://stackoverflow.com/questions/4361459/php-pdo-charset-set-names – Raymond Nijland Feb 21 '17 at 12:26
  • @RaymondNijland Thank you very much! This thread helped me a lot and I have finally overcome my problem. Thanks again! –  Feb 21 '17 at 14:08

0 Answers0