bugraozkan/json-php

It allows you to create a PHP object and convert it to json.

1.0.1 2024-12-15 22:16 UTC

This package is auto-updated.

Last update: 2025-06-15 23:31:49 UTC


README

This library simplifies the json_encode function, making it easier to generate and send JSON responses in PHP.

Installation

Install the library via Composer:

composer require bugraozkan/json-php

Include the autoloader in your project:

require 'vendor/autoload.php';

Features

  • Easy: Simplified API for creating and sending JSON responses.
  • Quick: Built on PHP's json_encode for fast performance.
  • Secure: Automatically sets appropriate HTTP headers.
  • Flexible: Supports adding objects, properties, or arrays dynamically.
  • Configurable: Allows customization of JSON encoding options.
  • Compatible: Works seamlessly with JSONP and jQuery.

Note: Objects are optimized to leverage JSON's inherent object representation.

Usage Example

<?php
require 'src/ApiResponse.php';

use JsonPhp\ApiResponse;

// Create an API response instance
$response = ApiResponse::create();

// Add data to the response
$response->setData([
    'name' => 'Bugra',
    'surname' => 'Ozkan',
    'age' => 21
]);

// Set the HTTP status code
$response->setStatus(200);

// Send the JSON response
$response->send();

Advanced JSON Options

Sending Regular JSON

Use the send method to send a standard JSON response.

$response->send();
// Output: { "name": "Bugra", "surname": "Ozkan", "age": 21 }

Returning JSONP

To return a JSONP response, specify a callback function:

$response->sendHeaders(['Content-Type' => 'application/javascript']);
echo "callback(" . json_encode([
    'status' => 200,
    'data' => [
        'name' => 'Bugra',
        'surname' => 'Ozkan',
        'age' => 21
    ]
]) . ");";

Output:

callback({ "status": 200, "data": { "name": "Bugra", "surname": "Ozkan", "age": 21 }});

JSON Validation

To validate JSON, use the json_encode method to retrieve the JSON string and validate it:

$jsonString = json_encode([
    'name' => 'Bugra',
    'surname' => 'Ozkan',
    'age' => 21
]);

// Validate the JSON with an external library or tool

JSON Encoding Options

You can customize the JSON encoding options using constants from PHP's json_encode function. For example:

$response->setData([
    'name' => 'Bugra',
    'surname' => 'Ozkan',
    'age' => 21
]);
$response->sendHeaders(['Content-Type' => 'application/json']);
echo json_encode($response->data, JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);

Notes

  • This library is compatible with PHP 7.0 and later.
  • Default JSON encoding options are used unless specified otherwise.
  • Supports custom HTTP headers for enhanced flexibility.

For more details, refer to the PHP Documentation on JSON Encoding.