You are here

function _views_geojson_encode_formatted in Views GeoJSON 6

Same name and namespace in other branches
  1. 7 views_geojson.helpers.inc \_views_geojson_encode_formatted()

Encodes GeoJSON in a pretty-printed fashion.

1 call to _views_geojson_encode_formatted()
views-views-geojson-style.tpl.php in views/views-views-geojson-style.tpl.php

File

./views_geojson.module, line 231
Provide a GeoJSON Views feed style.

Code

function _views_geojson_encode_formatted($v, $depth = 0) {
  $base_indent = '  ';
  $eol = '<br />';
  $indent = str_repeat($base_indent, $depth);

  // This is based on the drupal_to_js() function.
  switch (gettype($v)) {
    case 'boolean':

      // Lowercase is necessary!
      return $v ? 'true' : 'false';
    case 'integer':
    case 'double':
      return $v;
    case 'resource':
    case 'string':
      $search = array(
        '"',
        chr(92),
        chr(8),
        chr(12),
        chr(13) . chr(10),
        chr(10),
        chr(13),
        chr(9),
      );
      $replace = array(
        '\\"',
        '\\',
        '\\b',
        '\\f',
        '\\n',
        '\\n',
        '\\r',
        '\\t',
      );
      $output = str_replace($search, $replace, $v);

      /* *
            $output = str_replace(array("\r", "\n", "<", ">", "&"),
                                 array('\r', '\n', '\x3c', '\x3e', '\x26'),
                                 addslashes($output));
      /* */
      return '"' . check_plain($output) . '"';
    case 'array':

      // Arrays in JSON can't be associative.  If the array is empty or if it
      // has sequential whole number keys starting with 0, it's not associative
      // so we can go ahead and convert it as an array.
      if (empty($v) || array_keys($v) === range(0, sizeof($v) - 1)) {
        $output = array();
        foreach ($v as $val) {
          $output[] = $indent . $base_indent . _views_geojson_encode_formatted($val, $depth + 1);
        }
        return '[' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . ']';
      }

    // Otherwise, fall through to convert the array as an object.
    case 'object':
      $output = array();
      foreach ($v as $key => $val) {
        $output[] = $indent . $base_indent . _views_geojson_encode_formatted(strval($key)) . ' : ' . _views_geojson_encode_formatted($val, $depth + 1);
      }
      return '{' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . '}';
    default:
      return 'null';
  }
}