Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active May 8, 2019 01:48
Show Gist options
  • Select an option

  • Save abelcallejo/66e55e01dc8a9e3f018b8048a7b78801 to your computer and use it in GitHub Desktop.

Select an option

Save abelcallejo/66e55e01dc8a9e3f018b8048a7b78801 to your computer and use it in GitHub Desktop.

The jsonld_encode() function on PHP

php

Encodes an object or an array into JSON-LD format

Problem

JSON-LD uses the at '@' character as part of the JSON key naming convention.

Algorithm

Use 2 underscores '__' as a temporary namespace for naming object keys in PHP. Then, the jsonld_encode() will take care of making it an at character '@'.

Syntax

jsonld_encode( $variable )

Example

<?php
  $data = new stdClass();
  $data->__context = "http://schema.org";
  $data->__type = "Thing";
  $data->name = "Tardigrade";
  $data->description = "A cuddly microscopic extremophile that looks like a bear";

  echo jsonld_encode( $data );
?>

Output

{
  "@context": "http://schema.org",
  "@type": "Thing",
  "name": "Tardigrade",
  "description": "A cuddly microscopic extremophile that looks like a bear"
}
function jsonld_encode($variable){
$initial = json_encode($variable);
return str_replace("__","@", $initial);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment