Search code examples
phpsanitizationbackslash

Remove backslashes in printed json string


I want to remove additional backslashes (\) from the path.

I have this code snippet.

$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);

When I print or echo, I get this output.

{"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"}

Even after using str_replace() I am getting additional backslashes (\) in the image path. I am unable to find where I am making a mistake.


Solution

  • I got the answer. trim($variable) has done the work for me.

    this is what i have done and its working.

    $imagePath='www.abc.com/hrm';
    $ppic1=$row['ppic'];
    $ppic21=$imagePath."/".trim($ppic1); // here trim($ppic1) removed that extra character (\) from the url.