我正在尝试通过http调用php脚本并从我计划进一步处理的地方接收一个json对象。
基本上,代码如下:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$version=$_GET["v"];
$product=$_GET["p"];
$stream=$_GET["s"];
$cmd=$_GET["c"];
$string = file_get_contents("http://localhost:82/releasenote/src/getTSBDetails.php?p=$product&v=$version&s=$stream&c=$cmd");
print_r($string);
exit();
} else {
print("2");
$string = file_get_contents('tsbDetails.json');
}
当在浏览器中直接调用get_file_contents http请求时,输出是json,但在尝试使用上面时没有响应。
答案 0 :(得分:2)
<?php
// JSon request format is :
// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}
// read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};
// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
$responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
}
// JSon response format is :
// [{"name":"eeee","email":"eee@zzzzz.com"},
// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
// set header as json![enter image description here][2]
header("Content-type: application/json");
// send response
echo json_encode($responses);
?>
[1]: http://i.stack.imgur.com/I7imt.jpg
[2]: http://i.stack.imgur.com/XgvOT.jpg
答案 1 :(得分:0)
首先,您应该确保您的变量可以在网址中使用:
$version=urlencode($_GET["v"]);
$product=urlencode($_GET["p"]);
$stream=urlencode($_GET["s"]);
$cmd=urlencode($_GET["c"]);
然后你应该检查你在$string
中读到的值是否有效json。您可以使用this answer。
然后,如果你的字符串包含有效的json,你应该echo
它。
最后,如果你总是期望你的脚本中有json,你也应该json_encode你的错误处理:
} else {
echo json_encode("2");
// $string = file_get_contents('tsbDetails.json'); /* commented out as you don't seem to use it */
}