我正在开展一个需要json api的项目,比如
{
"images":[
{"id":1,"name":"test1","url":"image url"},
{"id":2,"name":"test2","url":"image url"}
]
}
但是我得到了不同的网址格式以及我编写的代码
<?php
header('Content-Type: application/json');
function getJson(){
$array = array( 'images' => array(array( 'id' => 1, 'name' => 'test1', 'url' => $_SERVER['HTTP_HOST'].DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.'test1.jpg'),
array( 'id' => 2, 'name' => 'test2', 'url' => $_SERVER['HTTP_HOST'].DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.'test2.jpg')));
return $array;
}
$typeArray=null;
if(isset($_GET['request'])){
if($_GET['request']=='images'){
$typeArray=getJson();
}else{
$typeArray = array(array( 'status' => 'failed', 'message' => 'Invalid request url'));
}
}else{
$typeArray = array(array( 'status' => 'failed', 'message' => 'Invalid request url'));
}
echo json_encode($typeArray);
echo $_SERVER['SERVER_PROTOCOL'];
?>
但是我得到了
{"images":[{"id":1,"name":"test1","url":"picd.flynox.com\/test\/test1.jpg"},{"id":2,"name":"test2","url":"picd.flynox.com\/test\/test2.jpg"}]}HTTP/1.1
我已将此更改推送到测试服务器http://picd.flynox.com/api/test/images
答案 0 :(得分:1)
对于反斜杠,您可以将JSON_UNESCAPED_SLASHES作为第二个参数传递给json_encode(),如下所示:
json_encode($typeArray, JSON_UNESCAPED_SLASHES);
在php 5.4之前,你可能需要使用smth:
str_replace('\/','/',json_encode($typedArray));
对于http / https,你应该使用$ _SERVER [&#39; HTTPS&#39;]:
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.