1.20.x common.inc backdrop_json_encode($var, $pretty_print = FALSE)

Converts a PHP variable into its JavaScript equivalent.

We use HTML-safe strings, with several characters escaped.

Parameters

mixed $var: The variable to be encoded as JSON.

bool $pretty_print: Backwards-compatible pretty printing of the JSON string. This uses the JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE options to make the JSON more readable by humans, or emulates this functionality if running an older version of PHP.

Return value

string: The given $var encoded as a JSON string.

See also

backdrop_json_decode()

Related topics

File

includes/common.inc, line 5692
Common functions that many Backdrop modules will need to reference.

Code

function backdrop_json_encode($var, $pretty_print = FALSE) {
  if ($pretty_print) {
    if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
      $string = json_encode($var, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    else {
      $string = json_encode($var);
      // PHP 5.3 JSON_PRETTY_PRINT.
      $string = backdrop_json_format($string);
      // PHP 5.3 JSON_UNESCAPED_UNICODE.
      $string = backdrop_json_decode_unicode($string);
      // PHP 5.3 JSON_UNESCAPED_SLASHES.
      $string = str_replace('\/', '/', $string);
    }
    // Collapse empty brackets, needed for PHP 5.3.x - PHP 5.4.27 to be
    // consistent with PHP 5.4.28+.
    $string = preg_replace('/\[\n[\s]+\]/m', '[]', $string);
    return $string;
  }
  // The non-pretty JSON is HTML markup compatible, encoding <, >, ', &, and ".
  else {
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }
}