XML解析器和构建器的包装器

1.1.1 2023-01-15 06:01 UTC

This package is auto-updated.

Last update: 2024-09-08 09:50:53 UTC


README

从 wechatpay-php 项目中分离出来,用于通用用途。

GitHub actions Packagist Stars Packagist Downloads Packagist Version Packagist PHP Version Support Packagist License

安装

composer require thenorthmemory/xml

用法

use TheNorthMemory\Xml\Transformer;
$array = Transformer::toArray('<xml><hello>world</hello></xml>');
// print_r($array);
// Array
// (
//     [hello] => world
// )
$xml = Transformer::toXml($array);
// print_r($xml);
// <xml><hello>world</hello></xml>
$xml = <<<TencentCOSRequest
<Request>
<Operation>
 <WatermarkTemplateId>t146d70eb241c44c63b6efc1cc93ccfc5d</WatermarkTemplateId>
 <WatermarkTemplateId>t12a74d11687d444deba8a6cc52051ac27</WatermarkTemplateId>
</Operation>
</Request>
TencentCOSRequest;
$array = Transformer::toArray($xml);
// Array
// (
//     [Operation] => Array
//         (
//             [WatermarkTemplateId] => Array
//                 (
//                     [0] => t146d70eb241c44c63b6efc1cc93ccfc5d
//                     [1] => t12a74d11687d444deba8a6cc52051ac27
//                 )

//         )

// )
$xml1 = Transformer::toXml($array, true, true, 'Request');
// print_r($xml1);
// <Request>
//  <Operation>
//   <WatermarkTemplateId>
//    <item>t146d70eb241c44c63b6efc1cc93ccfc5d</item>
//    <item>t12a74d11687d444deba8a6cc52051ac27</item>
//   </WatermarkTemplateId>
//  </Operation>
// </Request>
$array['Operation']['WatermarkTemplateId'] = Transformer::wrap($array['Operation']['WatermarkTemplateId'], true, 'WatermarkTemplateId');
$xml2 = Transformer::toXml($array, true, true, 'Request');
// print_r($xml2);
// <Request>
// <Operation>
//  <WatermarkTemplateId>t146d70eb241c44c63b6efc1cc93ccfc5d</WatermarkTemplateId>
//  <WatermarkTemplateId>t12a74d11687d444deba8a6cc52051ac27</WatermarkTemplateId>
// </Operation>
// </Request>

API

Transformer::toArray(string $xml = '<xml/>')

将 XML string 解析为 array

Transformer::sanitize(string $xml = '<xml/>')

XML1.0 20081126 字符范围 中净化 XML string

Transformer::toXml(array $data, bool $headless = true, bool $indent = false, string $root = 'xml', string $item = 'item'): string

将数据 array 构建为 XML string

Transformer::wrap(array $data, bool $wrapped = false, string $label = 'item'): LabeledArrayIterator

使用 labelwrapped 标志包裹 array 数据。

许可

Apache-2.0 许可证