简体   繁体   中英

php web service encoding doesn't work with accent

I've made a little web service in php with slim framework it works unless one of the json fields of the json object returned contains a character like á,é,í,ó,ú ,the enconding of the database is ut8_spanish_ci and this is the web service code

<?php
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

require 'Slim/Slim.php';


\Slim\Slim::registerAutoloader();
//creamos el objeto app
$app = new \Slim\Slim();

//importamos los ficheros con las funciones necesarias
require 'db/db_handler.php';
require 'app/app.php';
//ejecutamos app
$app->run();

this is app.php

<?php
    $app->get('/getAll/:table', function ($table) use($app){
            $db = new Db_handler;
            $result = $db->select_all($table);
            while($row = $result->fetch_assoc()){
                $dependency[] = $row ;
            }
            $struct = array("Dependencies"=>$dependency);

            $app->response->headers->set("Content-type","application/json");
            $app->response->status(200);
            $app->response->body(json_encode($struct));
        }
    );

    $app->get(
        '/get/:table/:id', function ($table, $id) use($app){
            $db = new Db_handler;
            $result = $db->select($table, $id);
            $row = $result->fetch_assoc();

            $app->response->headers->set("Content-type","application/json");
            $app->response->status(200);
            $app->response->body(json_encode($row));

        }
    );
?>

and db_handler.php

<?php
    class Db_handler{
        private $driver;
        private $host;
        private $port;
        private $schema;
        private $username;
        private $password;
        private $mysqli;

        function Db_handler( $config_file = 'connection.ini' ){
            if(!$connection_data = parse_ini_file($config_file, true)) throw new exception("No se puedo abrir el fichero de configuracion ".$config_file." .");
            $this->driver = $connection_data["database"]["driver"];
            $this->host = $connection_data["database"]["host"];
            $this->port = $connection_data["database"]["port"];
            $this->schema = $connection_data["database"]["schema"];
            $this->username = $connection_data["database"]["username"];
            $this->password = $connection_data["database"]["password"];

        }

        function connect(){
            $this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->schema, $this->port);
            if ($this->mysqli->connect_errno) {
                echo "Fallo al conectar a MySQL: (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
            }
            $this->mysqli->query("set names utf8");
        }

        function close(){
            $this->mysqli->close();
        }

        function select_all($table){
            $this->connect();
            if(!$result = $this->mysqli->query("SELECT * FROM $table"))
                die('Ocurrió un error al conectar  [' . $db->error . ']');
            $this->close();

            return $result;
        }

        function select($table,$id){
            $this->connect();
            if(!$result = $this->mysqli->query("SELECT * FROM $table WHERE nombre = '$id'"))
                die('Ocurrió un error al conectar  [' . $db->error . ']');
            $this->close();

            return $result;
        }   
    }
?>

I dont know what DbHandler is but you should set encoding to your Db Connection because from what I see this may cause problem.

You have proper encoding to browser but wrong to DB.

You can do it with pure SQL with SET Names UTF-8

SET NAMES indicates what character set the client will use to send SQL statements to the server.

Also you should consider better autloading than "require" because it looks really bad. Slim can use composer to autoload classes with PSR-4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM