Skip to content
← Back to Functions
Code

Safe Json Encoder

Encodes arrays for JSON output with consistent flags and error handling.

Function signature

ogEncodeJsonResponse(payload = array(), metadata = array())

Categories

  • APIs and Webhooks

Parameters

payloadPayload to encode.metadataOptional status and message metadata. Recognized keys: `message`, `status`.

Return value

Short public-safe status message.

  • json
  • bytes

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Encodes arrays for JSON output with consistent flags and error handling.
 *
 * Primary use case: AJAX/API responses.
 * Typical inputs: payload, status metadata.
 * Typical output: JSON string.
 *
 * Implementation note: Use JSON_THROW_ON_ERROR where supported.
 *
 * @param array $payload Payload to encode.
 * @param array $metadata Optional status and message metadata.
 * @return array Structured result containing encoded JSON.
 */
function ogEncodeJsonResponse($payload = array(), $metadata = array()) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	if (!is_array($metadata)) {
		$metadata = array();
	}

	$status = 'success';
	if (!empty($metadata['status'])) {
		$status = (string)$metadata['status'];
	}

	$message = '';
	if (!empty($metadata['message'])) {
		$message = (string)$metadata['message'];
	}

	$response = array(
		'status' => $status,
		'message' => $message,
		'data' => $payload
	);

	$json = json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
	if ($json === false) {
		$result['message'] = 'JSON encoding failed: ' . json_last_error_msg();
		return $result;
	}

	$result['success'] = true;
	$result['message'] = 'JSON response encoded.';
	$result['data'] = array(
		'json' => $json,
		'bytes' => strlen($json)
	);

	return $result;
}