简体   繁体   English

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

[英]Can't get the proper URL in JSON using PHP

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: 但是在JSON编码之后,这就是我得到的:

[{
"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. 我想要类似www.website.net/images/1.jpg的URL。 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. 在这方面的任何帮助将不胜感激。

By default, json_encode() escapes slashes. 默认情况下, json_encode()转义斜杠。 If you don't want that, pass the JSON_UNESCAPED_SLASHES option as the 2nd parameter. 如果您不希望这样做,请传递JSON_UNESCAPED_SLASHES选项作为第二个参数。 It is available since PHP 5.4.0. 自PHP 5.4.0起可用。

Example: 例:

echo(json_encode($json_Array, JSON_UNESCAPED_SLASHES ));

For more information, see json_encode() . 有关更多信息,请参见json_encode()

Try doing something as this 尝试做这样的事情

    function request($query){
    $data = array();
    $index = 0;
    if($r = mysqli_query(self::$conn, $query)){
        while($row = @mysqli_fetch_array($r)){
            $data[$index] = $row;
            $index++;
        }
        return array("request"=>$r, "rows"=>json_decode(json_encode($data), true));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM