1. Go to this page and download the library: Download webfiori/jsonx 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/ */
$json = new Json();
// Indexed array
$json->addArray('tags', ['php', 'json', 'api']);
// Associative arrays are automatically encoded as JSON objects
$json->addArray('address', ['city' => 'Riyadh', 'country' => 'SA']);
echo $json;
use WebFiori\Json\Json;
use WebFiori\Json\JsonI;
class User implements JsonI {
public function __construct(
private string $username,
private string $email
) {}
public function toJSON(): Json {
return new Json(['username' => $this->username, 'email' => $this->email]);
}
}
$json = new Json();
$json->addObject('user', new User('ibrahim', '[email protected]'));
echo $json;
use WebFiori\Json\Json;
use WebFiori\Json\JsonIgnore;
use WebFiori\Json\JsonProperty;
class Product {
#[JsonProperty('product_sku')]
public string $sku = 'ABC-001';
#[JsonIgnore]
public string $internalCode = 'X-99';
private string $name;
private float $price;
public function __construct(string $name, float $price) {
$this->name = $name;
$this->price = $price;
}
public function getName(): string { return $this->name; }
public function getPrice(): float { return $this->price; }
#[JsonProperty('on_sale')]
public function getAvailable(): bool { return true; }
#[JsonIgnore]
public function getSecretMargin(): float { return 0.42; }
}
$json = new Json([], 'snake');
$json->addObject('product', new Product('Keyboard', 49.99));
echo $json;
$data = ['first-name' => 'Ibrahim', 'last-name' => 'Al-Shikh'];
echo new Json($data, 'none') . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}
echo new Json($data, 'camel') . "\n"; // {"firstName":"Ibrahim","lastName":"Al-Shikh"}
echo new Json($data, 'snake') . "\n"; // {"first_name":"Ibrahim","last_name":"Al-Shikh"}
echo new Json($data, 'kebab') . "\n"; // {"first-name":"Ibrahim","last-name":"Al-Shikh"}
$json = Json::decode('{"name":"Ibrahim","age":30}');
echo $json->get('name'); // Ibrahim
$json = Json::fromJsonFile('/path/to/file.json');
class User {
public function __construct(
private string $username,
private string $email
) {}
public function getUsername(): string { return $this->username; }
public function getEmail(): string { return $this->email; }
}
$user = Json::decodeAs('{"username":"ibrahim","email":"[email protected]"}', User::class);
echo $user->getUsername(); // ibrahim
use WebFiori\Json\JsonType;
class Order {
public function __construct(
private User $customer,
#[JsonType(LineItem::class, isArray: true)]
private array $items
) {}
}
$order = Json::decodeAs($jsonString, Order::class);
$order->getCustomer(); // User instance
$order->getItems(); // LineItem[] array