Skip to content
Thomas Weinert edited this page Dec 15, 2016 · 2 revisions

JsonDOM

JsonDOM is an FluentDOM specific XML format for JSON. It keeps all information from the JSON , but allows for easy data extraction using Xpath. To allow for this it converts uses the keys from the JSON as tag names if possible.

The small example with the JSON example from Wikipedia:

$json = <<<JSON
{
  "firstName": "John",
  "lastName": "Smith",
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "fax",
      "number": "646 555-4567"
    }
  ]
}
JSON;

$document = FluentDOM::load($json, 'json');
$document->formatOutput = TRUE;
echo $document->saveXml();

XML Output:

<?xml version="1.0" encoding="UTF-8"?>
<json:json xmlns:json="urn:carica-json-dom.2013">
  <firstName>John</firstName>
  <lastName>Smith</lastName>
  <age json:type="number">25</age>
  <address>
    <streetAddress>21 2nd Street</streetAddress>
    <city>New York</city>
    <state>NY</state>
    <postalCode json:type="number">10021</postalCode>
  </address>
  <phoneNumbers json:type="array">
    <_>
      <type>home</type>
      <number>212 555-1234</number>
    </_>
    <_>
      <type>fax</type>
      <number>646 555-4567</number>
    </_>
  </phoneNumbers>
</json:json>

This allows for really easy access to the data using Xpath:

$document = FluentDOM::load($json, 'json');
var_dump(
  $document('string(/*/phoneNumbers/*[type="home"]/number)')
);
// Output: string(12) "212 555-1234"

As you can see a root element json in the namespace urn:carica-json-dom.2013 is added. This fulfills the XML condition of a single document element. The type attribute is added if the type can not be inferred from the child nodes itself. A name attribute would be added if the key from JSON could not be used as the tag name.

$document = FluentDOM::load(["example name" => 42], 'json');
$document->formatOutput = TRUE;
echo $document->saveXml();
<json:json xmlns:json="urn:carica-json-dom.2013">
  <examplename json:name="example name" json:type="number">42</examplename>
</json:json>
Clone this wiki locally