Php 我编写了这个简单的Restful web服务,得到了一个空白响应。为什么?
我正在学习用PHP编写Restful Web服务。因此,我根据视频教程编写了以下基本Web服务。问题是当我试图通过Php 我编写了这个简单的Restful web服务,得到了一个空白响应。为什么?,php,web-services,rest,restful-architecture,restful-url,Php,Web Services,Rest,Restful Architecture,Restful Url,我正在学习用PHP编写Restful Web服务。因此,我根据视频教程编写了以下基本Web服务。问题是当我试图通过http://localhost/Test8/?name=c(因为我的index.php位于Test8目录)URL中,我得到一个空白页面 但是当视频中的导师使用http://localhost/rest/?name=c(因为他们的index.php位于rest目录中),他们在网页中获得了{“status”:200,“status\u message”:“Book found”,“da
http://localhost/Test8/?name=c
(因为我的index.php
位于Test8
目录)URL中,我得到一个空白页面
但是当视频中的导师使用http://localhost/rest/?name=c
(因为他们的index.php
位于rest
目录中),他们在网页中获得了{“status”:200,“status\u message”:“Book found”,“data”:348}
。
我错过了什么?
index.php:
<?php
//Process client's request (via URL)
header("Content-Type:application/json");
if ( !empty($GET['name']) ) {
$name = $GET['name'];
$price = get_price($name);
if (empty($price)) {
//Book not found
deliver_response(200, 'Book not found!', NULL);
} else {
//Send the response with book price
deliver_response(200, 'Book found', $price);
}
} else {
//throw invalid request
deliver_response(400, "Invalid Request", NULL);
}
//API Functions
function get_price($bookRequested) {
$books = array(
'Java' => 999,
'C' => 348,
'PHP' =>500
);
foreach ($books as $book=>$price) {
if ($book == $bookRequested) {
return $price;
}
}
}
function deliver_response($status, $status_message, $data) {
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
}
?>
至
并且浏览器打印的
$GET[“name”]为空
您的传递响应()
函数实际上不会将结果发送到浏览器。它只是将$response
编码为JSON,并将其存储在$JSON\u response
中
尝试添加echo$json\u响应代码>到该函数的末尾
然后,访问您的URL:我看到您的代码没有使用json编码将PHP数组更改为json。也许值得尝试添加json_encode($price)。就个人而言,我从不使用deliver response,因此我不知道是否需要转换数组。通常我只是回显json编码的数组。这对我来说更简单。它是$\u GET而不是$GET@Bharata非常感谢。请看我问题中的编辑。谢谢。你能看到我问题中的编辑吗?$GET
为空=syes,我刚刚添加了关于$\u GET而不是$GET的评论
if ( !empty($GET['name']) ) {
...
} else {
//throw invalid request
...
}
if ( !empty($GET['name']) ) {
echo '$GET["name"] is NOT empty';
...
} else {
echo '$GET["name"] IS empty';
//throw invalid request
...
}