carica / jsondom
Read JSON into DOM
dev-master
2014-02-18 09:17 UTC
Requires
- php: >=5.4
This package is auto-updated.
Last update: 2024-10-29 04:36:21 UTC
README
License: The MIT License
Copyright: 2013-2014 Thomas Weinert thomas@weinert.info
Carica JsonDOM converts JSON into a XML DOM. The generated XML is wellformed and contains additional JSON specific data in a separate namespace.
Why not use JSON directly?
Because it is a lot of work. You need to check if elements exists, lists are empty, check conditions ... It is easier if you can use a query language, like Xpath.
Example
Use Xpath to fetch data from a JSON:
<?php
$reader = new Carica\JsonDOM\Reader($json);
$xpath = new DOMXpath($reader->asDom());
var_dump(
$xpath->evaluate('string(/*/phoneNumbers/*[type="home"]/number)')
);
// string(12) "212 555-1234"
JSON (from Wikipedia)
{
"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"
}
]
}
XML
<?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>
Create Json from XML
You can convert it back, or generate an JSON from any XML DOM. Node attributes will be ignored and duplicates will override the previous key.
<?php
echo 'XML -> JSON: ', "\n";
$writer = new Carica\JsonDOM\Writer($dom);
echo json_encode($writer, JSON_PRETTY_PRINT);
Installation
Carica JsonDOM is available on Packagist. Use Composer to add it as a dependency into your own projects.