duandui2803 2017-01-21 18:12
浏览 68
已采纳

无法使用PHP在JSON中获取正确的URL

I am trying to get something like this:

[{
    "id": "1",
    "url": {
        "small": "http://website/images/image.jpg",
        "large": "http://website/images/image.jpg"
    }, 
}]

My code is:

 <?php
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
define('SITE_ROOT', "www.website.net/images/");


$con = mysqli_connect('localhost','test','test','test');
$sql="SELECT * FROM images";
$result=mysqli_query($con,$sql);
$response=array();

while ($row = mysqli_fetch_array($result)) {
 $turl = SITE_ROOT.$row['id'].".jpg";
 $url = str_replace("\/", "\\", $turl);
 $json_Array[] = array('id'=>$row[id],'url'=>array('small'=>$url.$row[src],'large'=>$url.$row[src]));
}

echo(json_encode($json_Array));
mysqli_close($con);
?>

But after JSON Encoding, this is what I get:

[{
"id":"1",
"url":{
     "small":"www.website.net\/images\/1.jpg",
     "large":"www.website.net\/images\/1.jpg"
      }
 },
 {"id":"2",
"url":{
     "small":"www.website.net\/images\/2.jpg",
     "large":"www.website.net\/images\/2.jpg"}
}]

I want the URL like www.website.net/images/1.jpg. I even tried using:

 $turl = SITE_ROOT.$row['id'].".jpg";
 $url = str_replace("\/", "\\", $turl);

But still getting those /. Any kind of help in this regard would be appreciated.

  • 写回答

2条回答 默认 最新

  • doupuxuan5784 2017-01-21 18:40
    关注

    By default, json_encode() escapes slashes. If you don't want that, pass the JSON_UNESCAPED_SLASHES option as the 2nd parameter. It is available since PHP 5.4.0.

    Example:

    echo(json_encode($json_Array, JSON_UNESCAPED_SLASHES ));
    

    For more information, see json_encode().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?