删除打印的json字符串中的反斜杠

问题描述 投票:0回答:2

我想从路径中删除额外的反斜杠 (

\
)。

我有这个代码片段。

$imagePath = '/images/';
$query = mysqli_query($conn, "select sid,fname,mname,lname,did,ppic from hrm_staff");
 
if (mysqli_num_rows($query) > 0) {
  $response["hrm_staff"] = array();
 
 
  while ($row = mysqli_fetch_array($query)) {
     
     $recp = array();
     $recp["sid"] = $row["sid"];
     $fullName = $row['fname'] . "" . $row['mname'] . "" . $row['lname'];
     
     $recp["fname"] = $fullName;
     $recp["did"] = $row['did'];
      
     $ppic = $row['ppic'];
     
     $ppic = $imagePath.$ppic;
     $ppic = str_replace('\\', '', $ppic);
    
     $recp["ppic"] = $ppic;
 
     array_push($response["hrm_staff"], $recp);
  }

  echo json_encode($response);

当我

print
echo
时,我得到这个输出。

{"hrm_staff":[
    {"sid":"1","fname":"GaneshMB","did":"6","ppic":"\/images\/ prof_pic\/sb.jpg"},
    {"sid":"2","fname":"SwatiK","did":"5","ppic":"\/images\/ prof_pic\/ulogo.png"},
    {"sid":"3","fname":"KomalC","did":"2","ppic":"\/images\/ prof_pic\/p1.jpg"},
    {"sid":"4","fname":"KarthikR","did":"2","ppic":"\/images\/ prof_pic\/p3.jpg"},
    {"sid":"5","fname":"RenuP","did":"5","ppic":"\/images\/ prof_pic\/p6.jpg"},
    {"sid":"6","fname":"RahulMA","did":"5","ppic":"\/images\/ prof_pic\/p4.jpg"}
 ],"success":1,"message":"display records"}

即使在使用

str_replace()
之后,我在图像路径中也会收到额外的反斜杠 (
\
)。我找不到我哪里出错了。

php sanitization backslash
2个回答
0
投票

在 json 格式上使用

json_decode()
。这应该可以解决问题。

$a = '{"hrm_staff":[
{"sid":"1","fname":"GaneshMB","did":"6","ppic":"\/images\/     prof_pic\/sb.jpg"},
{"sid":"2","fname":"SwatiK","did":"5","ppic":"\/images\/ prof_pic\/ulogo.png"},
{"sid":"3","fname":"KomalC","did":"2","ppic":"\/images\/ prof_pic\/p1.jpg"},
{"sid":"4","fname":"KarthikR","did":"2","ppic":"\/images\/ prof_pic\/p3.jpg"},
{"sid":"5","fname":"RenuP","did":"5","ppic":"\/images\/ prof_pic\/p6.jpg"},
{"sid":"6","fname":"RahulMA","did":"5","ppic":"\/images\/ prof_pic\/p4.jpg"}
],"success":1,"message":"display records"}';


Print_r(json_decode($a));

请参阅演示此处


0
投票

我得到了答案。 trim($variable)已经为我完成了工作。

这就是我所做的及其工作。

$imagePath='www.abc.com/hrm';
$ppic1=$row['ppic'];
$ppic21=$imagePath."/".trim($ppic1); // here trim($ppic1) removed that extra character (\) from the url. 
© www.soinside.com 2019 - 2024. All rights reserved.