PHP code example of phputil / json

1. Go to this page and download the library: Download phputil/json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phputil / json example snippets



\phputil\JSON;

class Foo {
	private $a = 1;
	protected $b = 2;
	public $c = 3;
	
	function getA() { return $this->a; }
	function getB() { return $this->b; }
	function getC() { return $this->c; }
}

echo JSON::encode( new Foo() ); // { "a": 1, "b": 2, "c": 3 }

$obj = new stdClass();
$obj->name = 'Suzan';
$obj->age = 21;

echo JSON::encode( $obj ); // { "name": "Suzan", "age": 21 }

$obj1 = new stdClass();
$obj1->name = 'Bob';

$obj2 = new stdClass();
$obj2->name = 'Suzan';
$obj2->age = 21;

$json = JSON::encode( array( $obj1, $obj2 ) );
echo $json; // [ { "name": "Bob" }, { "name": "Suzan", "age": 21 } ]

$array = JSON::decode( $json );
var_dump( $array ); // array with the two PHP dynamic objects 

class Foo {
	private $a = 1;
	protected $b = 2;
	public $c = 3;
	
	function __call( $name, $args ) {
	    if ( 'getA' === $name ) { return $this->a; }
	    if ( 'getB' === $name ) { return $this->b; }
	    if ( 'getC' === $name ) { return $this->c; }
	}
}

echo JSON::encode( new Foo() ); // { "a": 1, "b": 2, "c": 3 }

$arr = array( 'name' => 'Bob', 'phone' => null, 'age' => 21 ); // phone is null
// true as the third argument makes encode() to ignore null values
echo JSON::encode( $arr, 'get', true ); // { "name": "Bob", "age": 21 }

JSON::addConversion( 'DateTime', function( $value ) {
	return $value->format( 'Y-m-d' ); // year-month-day
} );

$obj = new stdClass();
$obj->user = 'bob';
$obj->birthdate = new DateTime( "12/31/1980" ); // month/day/year

echo JSON::encode( $obj ); // { "user": "bob", "birthdate": "1980-12-31" }