JSONLD用于Google AMP,带有php-json-ld


JSONLD for Google AMP with php-json-ld

我在打印带有"php json ld"(github.com/digitalbazaar/php-json ld)的谷歌加速页面(AMP,www.ampproject.org)的正确JSONLD时遇到问题,如本例所述:github.com/ampproject/amphtml/blob/master/examples/metadata-examples/article-json-ld.AMP.html

更具体地说:我想知道如何使用php-json-ld:的函数添加"@type":"NewsArticle"

    $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>

有人能帮忙吗?

如果不需要转换JSON-LD,则不需要php-JSON-LD(或任何其他库)。将一个简单的关联数组序列化为JSON就足够了:

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

非常感谢Markus Lanthaler的回答,这对我帮助很大。我对他的回答只有一点补充:

如果使用post_title之类的变量,则会自动对字符进行编码,这将导致格式不正确的JSON-LD。应对这种情况的方法是首先解码标题中的变量:

html_entity_decode(get_the_title($post->ID),ENT_QUOTES,'UTF-8');

在回显json_encode时,您还应该添加json_UNESCAPED_UNCODE,以便进行正确的编码。

所以你的回声应该是这样的:

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);