### Install JsonLD using Composer Source: https://github.com/lanthaler/jsonld/blob/master/README.md This snippet demonstrates how to install the JsonLD library using Composer, a dependency manager for PHP. It requires PHP 5.3 or later. After installation, Composer's autoloader must be included in your project. ```bash composer require ml/json-ld ``` -------------------------------- ### Create and Manage JSON-LD Graph with Nodes Source: https://context7.com/lanthaler/jsonld/llms.txt Illustrates the programmatic creation of graphs and nodes using the object-oriented API. This includes managing relationships, types, and properties, with support for blank nodes and type-based queries. The example shows how to create typed nodes, link them, query nodes by type, check for node existence, and retrieve all nodes within a graph before serializing it to JSON-LD. ```php getGraph(); // Create typed nodes $personType = $graph->createNode('http://schema.org/Person'); $person = $graph->createNode('http://example.com/person/jane'); $person->addType($personType); $person->setProperty('http://schema.org/name', 'Jane Doe'); $person->setProperty('http://schema.org/email', 'jane@example.com'); // Create related blank node $address = $graph->createNode(); // Creates blank node $address->addType($graph->createNode('http://schema.org/PostalAddress')); $address->setProperty('http://schema.org/streetAddress', '123 Main St'); $address->setProperty('http://schema.org/addressLocality', 'Springfield'); // Link nodes $person->setProperty('http://schema.org/address', $address); // Query nodes by type $allPersons = $graph->getNodesByType('http://schema.org/Person'); foreach ($allPersons as $p) { echo "Person: " . $p->getId() . "\n"; } // Check if graph contains node if ($graph->containsNode('http://example.com/person/jane')) { echo "Person exists in graph\n"; } // Get all nodes in graph $allNodes = $graph->getNodes(); echo "Total nodes: " . count($allNodes) . "\n"; // Serialize to JSON-LD $serialized = JsonLD::toString($graph->toJsonLd(), true); echo $serialized; ?> ``` -------------------------------- ### Configure Custom JSON-LD Document Loader Source: https://context7.com/lanthaler/jsonld/llms.txt Shows how to set a custom document loader to control the fetching of remote documents and contexts. This allows for customized HTTP headers, caching mechanisms, or local file system resolution. The example implements a `CustomDocumentLoader` class that either loads from a local path or uses default HTTP fetching with custom authorization headers, and demonstrates setting it as the default loader or for specific operations. ```php [ 'method' => 'GET', 'header' => 'Authorization: Bearer my-token' ] ]; $context = stream_context_create($opts); $content = file_get_contents($url, false, $context); $document = json_decode($content); } $remoteDoc = new RemoteDocument($url); $remoteDoc->document = $document; return $remoteDoc; } } // Set as default loader JsonLD::setDefaultDocumentLoader(new CustomDocumentLoader()); // Now all operations use custom loader $expanded = JsonLD::expand('http://myapp.local/data.jsonld'); // Or use per-operation $options = ['documentLoader' => new CustomDocumentLoader()]; $compacted = JsonLD::compact('document.jsonld', 'context.jsonld', $options); ?> ``` -------------------------------- ### Include Composer Autoloader in PHP Source: https://github.com/lanthaler/jsonld/blob/master/README.md After installing JsonLD with Composer, this PHP code snippet shows how to include Composer's autoloader. This is essential for the JsonLD classes to be available in your project. ```php require('vendor/autoload.php'); ``` -------------------------------- ### Parse and Serialize N-Quads with PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Handles parsing N-Quads formatted text into quad objects and serializing quad objects back into N-Quads string format. This utility requires the ML/JsonLD and ML/IRI libraries. It supports basic quads, language-tagged strings, and typed literals, along with programmatic quad creation. ```php "value" . "hello"@en . "42"^^ . _:b0 . NQUADS; try { $quads = $nquads->parse($input); // Create new quad programmatically $subject = new IRI('http://example.com/subject'); $property = new IRI('http://example.com/predicate'); $object = new LanguageTaggedString('Bonjour', 'fr'); $graph = new IRI('http://example.com/mygraph'); $quads[] = new Quad($subject, $property, $object, $graph); // Serialize back to N-Quads $serialized = $nquads->serialize($quads); echo $serialized; } catch (ML\JsonLD\Exception\InvalidQuadException $e) { echo "Parse error: " . $e->getMessage(); } ?> ``` -------------------------------- ### Expand JSON-LD Document in PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Expands a JSON-LD document by applying its context to resolve terms and compact IRIs to absolute IRIs. It can load documents from files, strings, or URLs and accepts options for custom base IRIs. The output is the fully expanded form of the JSON-LD document. ```php 'http://schema.org/', '@type' => 'Person', 'name' => 'Jane Doe', 'jobTitle' => 'Professor' ]; $options = ['base' => 'http://example.com/']; $expanded = JsonLD::expand($input, $options); // Output: Array with expanded form // [ // { // "@type": ["http://schema.org/Person"], // "http://schema.org/name": [{"@value": "Jane Doe"}], // "http://schema.org/jobTitle": [{"@value": "Professor"}] // } // ] print JsonLD::toString($expanded, true); ``` -------------------------------- ### Load and Manipulate JSON-LD Document Source: https://context7.com/lanthaler/jsonld/llms.txt Demonstrates loading a JSON-LD document into an object-oriented structure, allowing direct manipulation of graphs and nodes. It covers retrieving nodes by ID, accessing and setting properties, creating blank nodes, linking nodes, and navigating reverse relationships. The loaded JSON-LD can then be serialized back to its string representation. ```php (object) ['name' => 'http://schema.org/name'], '@id' => 'http://example.com/person/1', 'name' => 'Jane Doe' ]; $doc = JsonLD::getDocument($input); // Get the default graph $graph = $doc->getGraph(); // Retrieve node by ID $node = $graph->getNode('http://example.com/person/1'); if ($node) { // Get property value $name = $node->getProperty('http://schema.org/name'); echo "Name: " . $name->getValue() . "\n"; // Add new property $node->setProperty('http://schema.org/age', 30); // Create and link a new blank node $newNode = $graph->createNode(); $newNode->setProperty('http://schema.org/name', 'Related Person'); // Link nodes together $node->addPropertyValue('http://schema.org/knows', $newNode); // Navigate reverse relationships $reverseLinks = $newNode->getReverseProperty('http://schema.org/knows'); // Returns $node } // Serialize back to JSON-LD $output = JsonLD::toString($graph->toJsonLd(), true); echo $output; ?> ``` -------------------------------- ### Compact JSON-LD Document in PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Compacts a JSON-LD document using a provided context to achieve the most compact representation. This involves shortening terms and compacting IRIs. The function supports loading contexts from files or using inline context objects and allows for options like compacting arrays and optimizing the output. ```php ['http://schema.org/Person'], 'http://schema.org/name' => [(object) ['@value' => 'Jane Doe']], 'http://schema.org/url' => [(object) ['@id' => 'http://example.com/jane']] ] ]; $context = (object) [ '@context' => (object) [ 'name' => 'http://schema.org/name', 'homepage' => (object) ['@id' => 'http://schema.org/url', '@type' => '@id'], '@vocab' => 'http://schema.org/' ] ]; $options = ['compactArrays' => true, 'optimize' => true]; $compacted = JsonLD::compact($input, $context, $options); // Output: Compacted object // { // "@context": {...}, // "@type": "Person", // "name": "Jane Doe", // "homepage": "http://example.com/jane" // } print JsonLD::toString($compacted, true); ``` -------------------------------- ### Convert RDF Quads to JSON-LD with PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Converts an array of RDF quads back into a JSON-LD document, outputting in expanded form. Options are available to control native type usage and RDF type representation. This process requires the ML/JsonLD library and PHP autoloader, and it can parse N-Quads strings. ```php . "Jane Doe" . "30"^^ . NQUADS; $nquads = new NQuads(); $quads = $nquads->parse($nquadsString); // Convert to JSON-LD with native types $options = [ 'useNativeTypes' => true, 'useRdfType' => false ]; $document = JsonLD::fromRdf($quads, $options); // Output: Expanded JSON-LD array // [ // { // "@id": "http://example.com/person/1", // "@type": ["http://schema.org/Person"], // "http://schema.org/name": [{"@value": "Jane Doe"}], // "http://schema.org/age": [{"@value": 30}] // } // ] print JsonLD::toString($document, true); ?> ``` -------------------------------- ### Node-centric API for JSON-LD Documents in PHP Source: https://github.com/lanthaler/jsonld/blob/master/README.md This PHP code demonstrates the node-centric API for interacting with JSON-LD documents using the JsonLD library. It covers retrieving documents, graphs, nodes, properties, linking nodes, and serializing the graph back to JSON-LD. ```php // Node-centric API $doc = JsonLD::getDocument('document.jsonld'); // get the default graph $graph = $doc->getGraph(); // get all nodes in the graph $nodes = $graph->getNodes(); // retrieve a node by ID $node = $graph->getNode('http://example.com/node1'); // get a property $node->getProperty('http://example.com/vocab/name'); // add a new blank node to the graph $newNode = $graph->createNode(); // link the new blank node to the existing node $node->addPropertyValue('http://example.com/vocab/link', $newNode); // even reverse properties are supported; this returns $newNode $node->getReverseProperty('http://example.com/vocab/link'); // serialize the graph and convert it to a string $serialized = JsonLD::toString($graph->toJsonLd()); ``` -------------------------------- ### JSON-LD Processor for PHP - API Reference Source: https://context7.com/lanthaler/jsonld/llms.txt This section covers the primary static API methods for processing JSON-LD documents. ```APIDOC ## JSON-LD Processor for PHP API Documentation This documentation covers the static API methods provided by the ML\JsonLD\JsonLD class for processing JSON-LD documents. ### Expand JSON-LD Document Expands a JSON-LD document by applying the document's context to resolve all terms and compact IRIs to absolute IRIs, removing context and producing the fully expanded form. ### Method GET ### Endpoint N/A (Static method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string|object|array) - The JSON-LD document to expand. Can be a file path (string), an object, or an array. - **options** (object, optional) - An object containing processing options, such as `base` for custom base IRI. ### Request Example ```php 'http://schema.org/', '@type' => 'Person', 'name' => 'Jane Doe', 'jobTitle' => 'Professor' ]; $options = ['base' => 'http://example.com/']; $expanded = JsonLD::expand($input, $options); print JsonLD::toString($expanded, true); ?> ``` ### Response #### Success Response (200) - **expanded_data** (array) - An array representing the fully expanded JSON-LD document. #### Response Example ```json [ { "@type": ["http://schema.org/Person"], "http://schema.org/name": [{"@value": "Jane Doe"}], "http://schema.org/jobTitle": [{"@value": "Professor"}] } ] ``` --- ### Compact JSON-LD Document Compacts a JSON-LD document according to a supplied context, applying the context to create the most compact representation possible with shortened terms and compact IRIs. ### Method GET ### Endpoint N/A (Static method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string|object|array) - The JSON-LD document to compact. Can be a file path (string), an object, or an array. - **context** (object|array) - The JSON-LD context to use for compaction. - **options** (object, optional) - An object containing processing options, such as `compactArrays` and `optimize`. ### Request Example ```php ['http://schema.org/Person'], 'http://schema.org/name' => [(object) ['@value' => 'Jane Doe']], 'http://schema.org/url' => [(object) ['@id' => 'http://example.com/jane']] ] ]; $context = (object) [ '@context' => (object) [ 'name' => 'http://schema.org/name', 'homepage' => (object) ['@id' => 'http://schema.org/url', '@type' => '@id'], '@vocab' => 'http://schema.org/' ] ]; $options = ['compactArrays' => true, 'optimize' => true]; $compacted = JsonLD::compact($input, $context, $options); print JsonLD::toString($compacted, true); ?> ``` ### Response #### Success Response (200) - **compacted_data** (object|array) - The compacted JSON-LD document. #### Response Example ```json { "@context": {...}, "@type": "Person", "name": "Jane Doe", "homepage": "http://example.com/jane" } ``` --- ### Flatten JSON-LD Document Flattens a JSON-LD document by collecting all nodes into a flat array and merging duplicate node definitions, optionally compacting the result with a provided context. ### Method GET ### Endpoint N/A (Static method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string|object|array) - The JSON-LD document to flatten. Can be a file path (string), an object, or an array. - **context** (object, optional) - The JSON-LD context to use for flattening and optional compaction. - **options** (object, optional) - An object containing processing options, such as `graph` to specify the graph type. ### Request Example ```php (object) ['name' => 'http://schema.org/name'], '@id' => 'http://example.com/person/1', 'name' => 'Jane', 'knows' => (object) [ '@id' => 'http://example.com/person/2', 'name' => 'Bob' ] ]; $context = (object) [ '@context' => (object) [ 'name' => 'http://schema.org/name', 'knows' => 'http://schema.org/knows' ] ]; $options = ['graph' => JsonLD::DEFAULT_GRAPH]; $flattened = JsonLD::flatten($input, $context, $options); print JsonLD::toString($flattened, true); ?> ``` ### Response #### Success Response (200) - **flattened_data** (object) - The flattened JSON-LD document, typically containing a `@graph` array. #### Response Example ```json { "@context": {...}, "@graph": [ {"@id": "http://example.com/person/1", "name": "Jane", "knows": {"@id": "http://example.com/person/2"}}, {"@id": "http://example.com/person/2", "name": "Bob"} ] } ``` ``` -------------------------------- ### Convert JSON-LD to RDF Quads with PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Converts a JSON-LD document into an array of RDF quads. Each quad includes subject, property, object, and an optional graph component. This function requires the ML/JsonLD library and PHP autoloader. The output can be serialized to N-Quads format. ```php (object) ['name' => 'http://schema.org/name'], '@id' => 'http://example.com/person/1', 'name' => 'Jane Doe' ]; $quads = JsonLD::toRdf($input); // Iterate through quads foreach ($quads as $quad) { echo 'Subject: ' . $quad->getSubject() . "\n"; echo 'Property: ' . $quad->getProperty() . "\n"; echo 'Object: ' . $quad->getObject()->getValue() . "\n"; if ($quad->getGraph()) { echo 'Graph: ' . $quad->getGraph() . "\n"; } } // Serialize to N-Quads format $nquads = new ML\JsonLD\NQuads(); $serialized = $nquads->serialize($quads); echo $serialized; // Output N-Quads string: // "Jane Doe" . ?> ``` -------------------------------- ### JSON-LD API Operations in PHP Source: https://github.com/lanthaler/jsonld/blob/master/README.md This PHP code illustrates common operations using the official JSON-LD API provided by the JsonLD library. It covers expanding, compacting, framing, flattening, and converting JSON-LD to RDF (quads), as well as serializing and parsing quads. ```php // Official JSON-LD API $expanded = JsonLD::expand('document.jsonld'); $compacted = JsonLD::compact('document.jsonld', 'context.jsonld'); $framed = JsonLD::frame('document.jsonld', 'frame.jsonld'); $flattened = JsonLD::flatten('document.jsonld'); $quads = JsonLD::toRdf('document.jsonld'); // Output the expanded document (pretty print) print JsonLD::toString($expanded, true); // Serialize the quads as N-Quads $nquads = new NQuads(); $serialized = $nquads->serialize($quads); print $serialized; // And parse them again to a JSON-LD document $quads = $nquads->parse($serialized); $document = JsonLD::fromRdf($quads); print JsonLD::toString($document, true); ``` -------------------------------- ### Frame JSON-LD Document with PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Frames a JSON-LD document using a supplied frame to restructure the data into a specific tree format. This operation requires the ML/JsonLD library and an autoloader. It takes an input JSON-LD document and a frame object, returning a framed document. ```php 'http://example.com/library/1', 'http://example.com/contains' => [(object) ['@id' => 'http://example.com/book/1']] ], (object) [ '@id' => 'http://example.com/book/1', 'http://schema.org/name' => [(object) ['@value' => 'The Great Gatsby']], 'http://schema.org/author' => [(object) ['@id' => 'http://example.com/person/fitzgerald']] ], (object) [ '@id' => 'http://example.com/person/fitzgerald', 'http://schema.org/name' => [(object) ['@value' => 'F. Scott Fitzgerald']] ] ]; // Create frame to embed books with authors $frame = (object) [ '@context' => (object) [ 'name' => 'http://schema.org/name', 'author' => 'http://schema.org/author', 'contains' => 'http://example.com/contains' ], '@type' => 'http://example.com/Library', 'contains' => (object) [ 'author' => (object) [] ] ]; $framed = JsonLD::frame($input, $frame); // Output: Hierarchical structure with embedded objects print JsonLD::toString($framed, true); ?> ``` -------------------------------- ### Flatten JSON-LD Document in PHP Source: https://context7.com/lanthaler/jsonld/llms.txt Flattens a JSON-LD document into a flat array of nodes, merging any duplicate definitions. The operation can optionally use a provided context to compact the resulting flattened graph. This function is useful for processing JSON-LD data into a more straightforward structure. ```php (object) ['name' => 'http://schema.org/name'], '@id' => 'http://example.com/person/1', 'name' => 'Jane', 'knows' => (object) [ '@id' => 'http://example.com/person/2', 'name' => 'Bob' ] ]; $context = (object) [ '@context' => (object) [ 'name' => 'http://schema.org/name', 'knows' => 'http://schema.org/knows' ] ]; $options = ['graph' => JsonLD::DEFAULT_GRAPH]; $flattened = JsonLD::flatten($input, $context, $options); // Output: Flattened array with separate nodes // { // "@context": {...}, // "@graph": [ // {"@id": "http://example.com/person/1", "name": "Jane", "knows": {"@id": "http://example.com/person/2"}}, // {"@id": "http://example.com/person/2", "name": "Bob"} // ] // } print JsonLD::toString($flattened, true); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.