graze/xml-utils

XML 工具,主要用于 XML 与数组之间的转换。

v1.1.0 2018-03-20 18:48 UTC

This package is auto-updated.

Last update: 2024-09-24 05:01:13 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

XML 工具,主要用于 XML 与数组之间的转换。

安装

通过 Composer

$ composer require graze/xml-utils

使用

将数组转换为 XML

$array = [
    'child1' => 111,
    'child2' => 222
];

$xmlElement = new SimpleXMLElement('<root/>');

$xmlConverter = new Graze\XmlUtils\XmlConverter();
$xmlConverter->addArrayAsChildren($array, $xmlElement);

echo $xmlElement->asXml();

结果

?xml version="1.0"?>
<root><child1>111</child1><child2>222</child2></root>

属性

使用 @attributes 键和一个属性名称 => 值数组来支持属性。

$array = [
    'child1' => [
        '@attributes' => [
            'id' => 123
        ]
    ]
];

结果

<child1 id="123"/>

带有值的属性

如果需要为具有属性的元素设置值,则应使用 @value 键。

$array = [
    'child1' => [
        '@attributes' => [
            'id' => 123
        ],
        '@value' => 'some description'
    ]
];

结果

<child1 id="123">some description</child1>

重复元素

使用索引数组支持重复元素。

$array = [
    'child' => [
        'first',
        'second'
    ]
];

结果

<child>first</child><child>second</child>

将 XML 转换为数组

$xml = '<root><child1>123</child1><child2 id="1"><subchild1>456</subchild1></child2></root>';

$xmlElement = new SimpleXMLElement($xml);

$xmlConverter = new XmlConverter();
$array = $xmlConverter->convertToArray($xmlElement);

结果

[
    'child1' => '123',
    'child2' => [
        '@attributes' => [
            'id' => '1'
        ],
        'subchild1' => '456'
    ]
];

格式化 XML

格式化 XML,使其更易于阅读。

$unformattedXml = '<?xml version="1.0" encoding="UTF-8"?><root><child1>123</child1><child2 attribute="1"><subchild1>456</subchild1></child2></root>';

$xmlFormatter = new XmlFormatter();
$formattedXml = $xmlFormatter->format($unformattedXml);

结果

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child1>123</child1>
  <child2 attribute="1">
    <subchild1>456</subchild1>
  </child2>
</root>

变更日志

有关最近更改的更多信息,请参阅 变更日志

测试

make build test

贡献

有关详细信息,请参阅 贡献指南

安全

如果您发现任何安全相关的问题,请通过电子邮件 security@graze.com 报告,而不是使用问题跟踪器。

致谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件