Search code examples
phpschema.orgjson-ldamp-html

JSONLD for Google AMP with php-json-ld


I have problems printing the correct JSONLD for Google Accelerated Pages (AMP, www.ampproject.org) with "php-json-ld" (github.com/digitalbazaar/php-json-ld) as documented in this example: github.com/ampproject/amphtml/blob/master/examples/metadata-examples/article-json-ld.amp.html

More specifically: I am wondering how to add the "@type": "NewsArticle" by using the functions of php-json-ld:

    $doc = (object)array(      
    "https://schema.org/article" => 'Article',
    "http://schema.org/name" => "Manu Sporny",
    "http://schema.org/url" => (object)array("@id" =>     "http://manu.sporny.org/"),
    "http://schema.org/image" => (object)array("@id" => "http://manu.sporny.org/images/manu.png")
);

    $context = (object)array(
    "article" => (object)array("https://schema.org/Article"),
    "name" => "http://schema.org/name",
    "homepage" => (object)array("@id" => "http://schema.org/url", "@type" => "@id"),
    "image" => (object)array("@id" => "http://schema.org/image", "@type" => "@id")
);

    //Print Json-LP
    echo '<script type="application/ld+json">';
    echo json_encode($jsonld_compacted, 
                JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    echo '</script>';

    //Result:
    <script type="application/ld+json">{
       "@context": "http://schema.org",
       "image": "http://manu.sporny.org/images/manu.png",
       "name": "Manu Sporny",
       "url": "http://manu.sporny.org/"
   }</script>

Can anyone help?


Solution

  • If you don't need to transform the JSON-LD, you don't need php-json-ld (or any other library). A simple associative array that you serialize as JSON is enough:

    $data = array(
      "@context" => "http://schema.org",
      "@type" => "NewsArticle",
      ...
    );
    
    ...
    
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);