PHP Classes

File: Readme.md

Recommend this page to a friend!
  Classes of Ramesh Narayan Jangid   PHP JSON Encode Large Data   Readme.md   Download  
File: Readme.md
Role: Documentation
Content type: text/markdown
Description: Readme
Class: PHP JSON Encode Large Data
Encode large arrays to JSON using less memory
Author: By
Last change: Typo changes
Date: 7 months ago
Size: 1,869 bytes
 

Contents

Class file image Download

JSON is a format for encoding data structures as strings. PHP can encode any variable type using the JSON format.

Suppose you want to encode an array with many elements. In that case, the PHP JSON encoding function can take a lot of memory because it needs to take a variable as a parameter with all the elements and create a string in memory with the result of the JSON encoding process.

This package provides a better solution that takes much less memory. It can encode one array element at a time and outputs it immediately without adding all elements to the array.

This way, the class does not store all array elements, and that will save a lot of memory, keeping the memory usage within limits set in the PHP configuration.

Example:

<?php
$sth = $db->select($sql);
$sth->execute($params);

$jsonEncode = new JsonEncode();

// For a single row

$jsonEncode->startAssoc();
foreach($sth->fetch(PDO::FETCH_ASSOC) as $key => $value) {
    $jsonEncode->addKeyValue($key, $value);
}
$jsonEncode->endAssoc();
// OR
$jsonEncode->encode($sth->fetch(PDO::FETCH_ASSOC));

// For multiple rows

$jsonEncode->startArray();
for(;$row=$sth->fetch(PDO::FETCH_ASSOC);) {
    $jsonEncode->encode($row);
}
$jsonEncode->endArray();

// For output of both assoc and simple array.
// Array inside Associative array.

$jsonEncode->startAssoc();
foreach($sth->fetch(PDO::FETCH_ASSOC) as $key => $value) {
    $jsonEncode->addKeyValue($key, $value);
}

$sth_2 = $db->select($sql_2);
$sth_2->execute($params_2);

$jsonEncode->startArray($assocKey);
for(;$row=$sth_2->fetch(PDO::FETCH_ASSOC);) {
    $jsonEncode->encode($row);
}
$jsonEncode->endArray();
$jsonEncode->endAssoc();

$jsonEncode = null;