PHP code example of asmi046 / laravel-jsonld

1. Go to this page and download the library: Download asmi046/laravel-jsonld 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/ */

    

asmi046 / laravel-jsonld example snippets


// config/jsonld.php
return [
    // Включить строгую валидацию (обязательные поля должны быть заполнены)
    'strict' => true,

    // Красивое форматирование JSON
    'pretty_print' => false,

    // Режим экранирования HTML: 'none', 'json_encode', 'htmlspecialchars'
    'escape_mode' => 'json_encode',

    // Флаги json_encode
    'json_flags' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
];

use Asmi\JsonLd\Facades\JsonLd;

// Person
$person = JsonLd::person()
    ->name('John Doe')
    ->jobTitle('Software Developer')
    ->email('[email protected]')
    ->url('https://johndoe.com')
    ->render();

// Organization
$org = JsonLd::organization()
    ->name('Acme Corporation')
    ->url('https://acme.com')
    ->logo('https://acme.com/logo.png')
    ->email('[email protected]')
    ->telephone('+1-555-0100')
    ->render();

// Article
$article = JsonLd::article()
    ->headline('Understanding JSON-LD')
    ->description('Learn how to use JSON-LD for structured data...')
    ->datePublished('2026-04-09')
    ->dateModified('2026-04-10')
    ->image('https://example.com/image.jpg')
    ->author(JsonLd::person()->name('Jane Smith'))
    ->render();

// Product
$product = JsonLd::product()
    ->name('Awesome Product')
    ->description('The best product ever')
    ->price(99.99)
    ->priceCurrency('USD')
    ->image('https://example.com/product.jpg')
    ->brand(JsonLd::organization()->name('Brand Inc'))
    ->url('https://example.com/product')
    ->render();

// WebSite
$website = JsonLd::website()
    ->name('My Website')
    ->url('https://example.com')
    ->description('Welcome to my website')
    ->logo('https://example.com/logo.png')
    ->render();

// LocalBusiness
$localBusiness = JsonLd::localBusiness()
    ->name('Кофейня на Арбате')
    ->url('https://coffeeshop.ru')
    ->telephone('+7-495-000-0000')
    ->address('Арбат, 10, Москва')
    ->openingHours('Mo-Fr 08:00-22:00')
    ->priceRange('$$')
    ->geo(['@type' => 'GeoCoordinates', 'latitude' => 55.7522, 'longitude' => 37.5722])
    ->paymentAccepted(['Cash', 'Credit Card'])
    ->render();

// TravelAgency
$travelAgency = JsonLd::travelAgency()
    ->name('Путешествия мечты')
    ->url('https://dream-travel.ru')
    ->telephone('+7-800-000-0000')
    ->email('[email protected]')
    ->openingHours('Mo-Su 09:00-21:00')
    ->areaServed(['Россия', 'Европа', 'Азия'])
    ->serviceType('Туристические туры')
    ->render();

// TouristTrip
$trip = JsonLd::touristTrip()
    ->name('Золотое кольцо на выходные')
    ->description('Культурный тур по древним городам России')
    ->startDate('2026-06-01')
    ->endDate('2026-06-03')
    ->touristType(['Семьи', 'Пары'])
    ->itinerary(['Москва', 'Сергиев Посад', 'Суздаль'])
    ->provider(JsonLd::travelAgency()->name('Путешествия мечты'))
    ->render();

// Создание сущности через метод make
$person = JsonLd::make('Person', [
    'name' => 'John Doe',
    'jobTitle' => 'Developer',
    'email' => '[email protected]',
])->render();

$org = JsonLd::make('Organization', [
    'name' => 'Acme Corp',
    'url' => 'https://acme.com',
])->render();

$localBusiness = JsonLd::make('LocalBusiness', [
    'name' => 'Кофейня на Арбате',
    'telephone' => '+7-495-000-0000',
    'openingHours' => 'Mo-Fr 08:00-22:00',
])->render();

$travelAgency = JsonLd::make('TravelAgency', [
    'name' => 'Путешествия мечты',
    'areaServed' => ['Россия', 'Европа'],
    'serviceType' => 'Туристические туры',
])->render();

$trip = JsonLd::make('TouristTrip', [
    'name' => 'Золотое кольцо на выходные',
    'startDate' => '2026-06-01',
    'endDate' => '2026-06-03',
    'touristType' => ['Семьи', 'Пары'],
])->render();

use Asmi\JsonLd\Facades\JsonLd;

$json = '{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Question?","acceptedAnswer":{"@type":"Answer","text":"Answer."}}]}';

// Рендер как HTML script tag
$script = JsonLd::raw($json)->render();

// Получить как нормализованный JSON / массив
$json = JsonLd::raw($json)->toJson();
$array = JsonLd::raw($json)->toArray();

// Fluent helper-функции
$person = jsonld_person()
    ->name('John Doe')
    ->jobTitle('Developer')
    ->render();

$org = jsonld_organization()->name('Acme Corp')->render();
$article = jsonld_article()->headline('My Post')->datePublished('2026-04-09')->render();
$product = jsonld_product()->name('Product')->price(99.99)->render();
$website = jsonld_website()->name('Site')->url('https://example.com')->render();
$localBusiness = jsonld_local_business()->name('Кофейня')->openingHours('Mo-Fr 08:00-22:00')->render();
$travelAgency = jsonld_travel_agency()->name('Агентство')->areaServed('Россия')->render();
$trip = jsonld_tourist_trip()->name('Тур')->startDate('2026-06-01')->render();

// Factory helper
$person = jsonld_make('Person', ['name' => 'John']);
$localBusiness = jsonld_make('LocalBusiness', ['name' => 'Кофейня']);
$travelAgency = jsonld_make('TravelAgency', ['name' => 'Агентство']);
$trip = jsonld_make('TouristTrip', ['name' => 'Тур']);

// Raw helper — произвольная JSON-строка
$script = jsonld_raw('{"@context":"https://schema.org","@type":"WebPage","name":"Page"}')->render();

$person = JsonLd::person()->name('John Doe');

// Рендер как HTML script tag (по умолчанию)
echo $person->render();

// Получить как JSON-строку
$json = $person->toJson();

// Получить как PHP-массив
$array = $person->toArray();

use Asmi\JsonLd\Exceptions\ValidationException;

try {
    $person = JsonLd::person()->render(); // Отсутствует обязательное поле 'name'
} catch (ValidationException $e) {
    $errors = $e->getErrors();
    // ['name' => "Required field 'name' is missing."]
}

// In config/jsonld.php
'strict' => false,

// Или временно
config(['jsonld.strict' => false]);
$person = JsonLd::person()->render(); // Исключение выброшено не будет
bash
php artisan vendor:publish --tag=jsonld-config
bash
php vendor/bin/phpunit

# С coverage
php vendor/bin/phpunit --coverage-html coverage