我已经在php中创建了一个带有超薄框架的小型Web服务,除非返回的json对象的一个json字段包含一个像á,é,í,ó,ú这样的字符,数据库的enconding是ut8_spanish_ci这是网络服务代码
<?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();
这是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));
}
);
?>
和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;
}
}
?>
答案 0 :(得分:1)
我不知道DbHandler是什么,但你应该为你的Db连接设置编码,因为从我看到这可能会导致问题。
您对浏览器进行了正确的编码,但对DB有误。
您可以使用SET Names UTF-8
SET NAMES表示客户端将用于将SQL语句发送到服务器的字符集。
另外你应该考虑更好的自动加载而不是&#34;要求&#34;因为它看起来很糟糕Slim可以使用composer来自动加载PSR-4类