gelight / php-json2sml
PHP 库,用于将 JSON 转换为 SML
0.0.1
2021-08-15 18:51 UTC
Requires
- stenway/sml: ^0.0.3
This package is auto-updated.
Last update: 2024-09-16 01:52:04 UTC
README
将 JSON 转换为 SML 文档。
SML 是什么?
使用方法
给定 JSON 结构
<?php include_once "vendor/autoload.php"; use GELight\conversion\{JsonToSmlConverter}; $json = <<<JSON { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 27, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [ "Aaron" ], "spouse": true } JSON; $converter = new JsonToSmlConverter(); $doc = $converter::convert(json_decode($json)); $root = $doc->getRoot(); // Returns the first value of attribute "lastName" echo $root ->attribute("lastName") ->getValues()[0]; // Returns the first value of attribute "city" in element "address" echo $root ->element("address") ->attribute("city") ->getValues()[0]; // Returns the first value of attribute "number" of second element "phoneNumbers" echo $root ->element("phoneNumbers") ->elements()[1] ->attribute("number") ->getValues()[0]; // Returns the first value of attribute "children" echo $root ->attribute("children") ->getValues()[0];
结果
Smith New York 646 555-4567 Aaron
生成的 SML 文档结构作为字符串输出
# PHP $doc->toString();
sml firstName John lastName Smith isAlive 1 age 27 address streetAddress "21 2nd Street" city "New York" state NY postalCode 10021-3100 end phoneNumbers phoneNumber type home number "212 555-1234" end phoneNumber type office number "646 555-4567" end end children Aaron spouse 1 end
文档
JsonToSmlConverter
创建一个新的 JSON 到 SML 转换器实例
$converter = new JsonToSmlConverter();
convert
静态方法 "convert" 将您的 JSON 转换为 SML 文档。
convert(object $jsonObject): SmlDocument
$smlDocument = $converter::convert(json_decode($json));