我正在尝试使用JSON输出构建API,第二个函数正在生成所需的输出,但我无法从Web调用它。而第一个函数按预期返回大量文本。我使用不兼容的东西吗?我在Ubuntu 14.04服务器上使用的是PHP 5.5.9版本。
我可以在终端和浏览器中查看此功能的结果;
<?php
class ArticlesAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
while ($row = $results->fetch_assoc()) {
echo $row['article_id'];
echo $row['title'];
echo $row['summary'];
}
$results->close();
}
}
$api = new ArticlesAPI;
$api->top();
?>
此功能仅在终端中返回结果;
<?php
class ArticleAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
$articles = array();
while($article = $results->fetch_assoc()){
$article_id = $article['article_id'];
$articles[$article_id][] = $article['title'];
$articles[$article_id][] = $article['summary'];
}
$results->close();
$db->close();
$json = json_encode($articles);
echo $json;
}
}
$api = new ArticleAPI;
$api->top();
?>
答案 0 :(得分:2)
<?php echo 'hello world';
并查看输出是否正确。如果你通过浏览器打开它,你看到的不仅仅是hello world,那么PHP解析器就没有启用。application/json
exit
并在之后检查脚本。error_reporting(E_ALL);
和ini_set('display_errors', 1);
,以检查是否有错误。