【发布时间】:2018-10-08 01:26:23
【问题描述】:
我无法让我的 PHP Rest API 工作,它只是返回空正文 带有成功的 HTTP 请求 (200)。
当我只是回显某些内容时,它会很好地返回。我正在使用 Slim(PHP 微框架)MySQL,apache。数据库表在 phpmyadmin 中创建。
index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../src/config/db.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
// Customer Routes
require '../src/routes/dates.php';
$app->run();
db.php 它还包含 dbhost、dbuser、dbpass 和 dbname 上面的变量
<?php
class db
{
// Properties
var $dbhost = 'localhost';
var $dbuser = 'root';
var $dbpass = 'parool1';
var $dbname = 'slimapp';
// Connect
public function connect()
{
$mysql_connect_str = "mysql:host=$this->dbhost;dbname=$this->dbname";
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
}
dates.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
// Get All Calendar Dates
$app->get('/api/date', function (Request $request, Response $response) {
$sql = "SELECT * FROM `calendardates`";
try {
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$dates = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($dates);
} catch (PDOException $e) {
echo '{"error": {"text": ' . $e->getMessage() . '}';
}
});
将数据库表的排序规则更改为 utf8(如果您想在数据库表中使用“ö、ä、ü”等字符)。
我变了
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass);
到
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
解决问题。
【问题讨论】:
-
你能添加
var_dump($dates)输出吗? -
你试过
return $response->withJson($dates)吗? -
var_dump($dates) 返回:array(2) { [0]=> object(stdClass)#65 (3) { ["id"]=> string(1) "1" [ "date_title"]=> string(9) "Nuudip�ev" ["date_date"]=> string(10) "1515283200" } [1]=> object(stdClass)#66 (3) { ["id"] => string(1) "2" ["date_title"]=> string(13) "Taliharjap�ev" ["date_date"]=> string(10) "1515888000" } }