Wie entferne ich den Backslash bei der json_encode()-Funktion?

Sie können die Option JSON_UNESCAPED_SLASHES in der Funktion json_encode() verwenden, um zu verhindern, dass Backslashes zur JSON-Zeichenfolge hinzugefügt werden.

<?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;

Für PHP-Versionen < 5.4 verwenden Sie dies:

<?php

// Define an array of data to encode as JSON
$data = [
  'name' => 'John Doe',
  'age' => 30,
  'email' => '[email protected]',
  'favorite_quotes' => [
    "We can't solve problems by using the same kind of thinking we used when we created them. - Albert Einstein",
    "The greatest glory in living lies not in never falling, but in rising every time we fall. - Nelson Mandela",
  ],
];

// Encode the array as a JSON string, with Unicode escape sequences replaced
$json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$json = preg_replace_callback(
  '/\\\\u([a-f0-9]{4})/i',
  function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
  },
  $json
);

// Output the resulting JSON string
echo $json;