PHP code example of brick / schema

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

    

brick / schema example snippets


use Brick\Schema\SchemaReader;

// read all available formats:
$schemaReader = SchemaReader::forAllFormats();

// or read a single format:
// $schemaReader = SchemaReader::forMicrodata();
// $schemaReader = SchemaReader::forRdfaLite();
// $schemaReader = SchemaReader::forJsonLd();

// The URL the document was retrieved from. This will be used only to resolve relative
// URLs in property values. No attempt will be performed to connect to this URL.
$url = 'https://example.com/product/123';

$things = $schemaReader->readHtml($html, $url);               // An HTML document as a string
// or $things = $schemaReader->readHtmlFile($htmlFile, $url); // A path to an HTML file
// or $things = $schemaReader->read($domDocument, $url);      // A DOMDocument instance

use Brick\Schema\Interfaces as Schema;

foreach ($things as $thing) {
    if ($thing instanceof Schema\Product) {
        // Your IDE should now provide autocompletion for available Product properties:
        // category, color, gtin, sku, offers, ...

        foreach ($thing->offers as $offer) {
            // You should always check if the Thing matches the expected type,
            // even if the schema.org property documents a single type (here, Offer).
            // See the Caveats section below for an explanation why.

            if ($offer instanceof Schema\Offer) {
                // Yes! we do have an offer, let's check its price.
                // Don't forget that all properties have zero or more values, let's take the first one:

                $price = $offer->price->getFirstValue();

                // For the same reason as above (see Caveats), always check the type of the value,
                // it could very well be a nested Thing instance, or null if there is no value.

                if (is_string($price)) {
                    echo $price;
                }

                // There are also helper functions in the SchemaTypeList object when you expect a string.
                // For example, this will return the first string value, or null if not found:

                $priceCurrency = $offer->priceCurrency->toString();

                if ($priceCurrency !== null) {
                    echo $priceCurrency;
                }
            }
        }
    }
}