W3docs

How to remove backslash on json_encode() function?

You can use the JSON_UNESCAPED_SLASHES option in the json_encode() function to prevent backslashes from being added to the JSON string.

You can use the JSON_UNESCAPED_SLASHES option in the json_encode() function to prevent backslashes from being added to the JSON string.

Example of using the JSON_UNESCAPED_SLASHES option in the json_encode() function to prevent backslashes from being added to the JSON string in PHP

<?php

// Define an array of data to encode as JSON
$data = [
  'name' => 'John Doe',
  'age' => 30,
  'email' => '[email protected]',
];

// Encode the array as a JSON string, with slashes unescaped
$json = json_encode($data, JSON_UNESCAPED_SLASHES);

// Output the resulting JSON string
echo $json;

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

For PHP versions prior to 5.4, use str_replace() to remove the escaped slashes after encoding:

Example of using str_replace() to remove backslashes from the JSON string in PHP < 5.4

<?php

// Define an array of data to encode as JSON
$data = [
  'name' => 'John Doe',
  'age' => 30,
  'email' => '[email protected]',
];

// Encode the array as a JSON string
$json = json_encode($data);

// Remove escaped forward slashes
$json = str_replace('\/', '/', $json);

// Output the resulting JSON string
echo $json;