2014-03-26 173 views
0

我的工作,其中需要一個JSON API類似刪除反斜槓,並添加協議

{ 
    "images":[ 
      {"id":1,"name":"test1","url":"image url"}, 
      {"id":2,"name":"test2","url":"image url"} 
      ] 
} 

一個項目,但我得到不同的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

爲什麼'echo $ _SERVER ['SERVER_PROTOCOL'];'到底? –

+0

@ DurgeshChaudhary,我需要URL像「http:// picd.flynox.com」,但我通過使用$ _SERVER ['HTTP_HOST']得到「picd.flynox.com」。我的意思是,如何添加像http協議://或https://但我不能硬編碼。 –

回答

1

對於反斜線,你可以通過JSON_UNESCAPED_SLASHES作爲第二個參數json_encode()是這樣的:

json_encode($typeArray, JSON_UNESCAPED_SLASHES); 

之前的是PHP 5.4,你可能需要使用不便,如:

str_replace('\/','/',json_encode($typedArray)); 

對於HTTP/https您應該使用$ _SERVER ['HTTPS']:

'HTTPS' 
Set to a non-empty value if the script was queried through the HTTPS protocol. 
+0

感謝@blu,它工作的很好。可以建議我製作完整的網址「http:// picd.flynox.com」。我正在嘗試$ _SERVER ['HTTP_HOST'],但這還不夠。 –

+0

我已經在我的答案中寫過 - drop $ _SERVER ['HTTP_HOST']並使用如下所示的smth:_ $ url =((0 blue