damijanc / simple-xml
用于生成XML的DomDocument包装器
Requires
- php: >=8.2
- ext-dom: *
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-08-30 14:37:41 UTC
README
PHP (https://php.ac.cn/manual/en/class.domdocument.php) DOMDocument的简单包装器
大约11年后,这个库终于得到了更新。它使用了PHP的一个不错特性 - 属性 :D
关于XML本身的一些内容
有效的XML需要以xml版本和编码声明开始,如 <?xml version="1.0" encoding="utf-8"?>
。没有它的XML是无效的。
库默认使用UTF-8编码。所以请确保您的所有字符串都已正确编码。
XML支持多种类型的文本:文本、CDATA和一个元素。
CDATA部分中的所有内容都将被解释为文本字符串。例如 <![CDATA[<sender>John Smith</sender>]]>
将被解释为 <sender>John Smith</sender>
,作为文本字符串。为了与 XML规范 兼容,如果您的字符串包含 <、>、& 等字符,则可以使用CDATA。
文本属性将确保相同的字符将被转义。 &
将成为 &
,>
将成为 >
,而 <
将成为 <
。您可以根据需要使用。
如果没有选择任何内容,则将使用原始值。也许我以后会添加一些格式化程序,如日期和货币,因为它们在PHP中受支持。
安装
composer require damijanc/simple-xml
用法
我们需要定义一个带有属性的类,以告诉库我们想要什么样的XML。目前不支持设置器和获取器,但我可能以后会添加这些功能。如果属性是数组,我们期望有一个类的数组,这些类被类似地装饰了属性
在示例中,我们有一个书籍集合。为此,我们需要定义一个集合类books和一个books类,如下面的示例所示。
use damijanc\SimpleXml\Attribute\Node; use damijanc\SimpleXml\Attribute\Property; #[Node('books')] #[Property('type', 'fiction')] class Books { public array $books; }
use damijanc\SimpleXml\Attribute\CData; use damijanc\SimpleXml\Attribute\Node; use damijanc\SimpleXml\Attribute\Property; #[Node('book')] class Book { #[Node('author')] #[Property('author', null)] public string $author; #[Node('title')] #[CData()] public string $title; #[Node('price')] public string $price; }
输出
<?xml version="1.0" encoding="utf-8"?> <books type="fiction"> <book> <author author="George Orwell">George Orwell</author> <title>1984</title> </book> <book> <author author="Lojze Slak">Lojze Slak</author> <title>S harmoniko po svetu</title> </book> <book> <author author="Isaac Asimov">Isaac Asimov</author> <title>Foundation</title> <price>$15.61</price> </book> <book> <author author="Robert A Heinlein">Robert A Heinlein</author> <title>Stranger in a Strange Land</title> <price>$43.29</price> </book> </books>
关于注释的说明:由于注释可以出现在XML的任何地方,因此很难预测用户的意图。我决定在节点属性级别添加注释支持
例如
#[Node('title')] #[Comment('This is a comment')] public string $title;
将产生
<title><!--This is a comment-->1984</title>
我可能以后会改变这种实现。目前,我没有任何实际用例。
支持的属性
#[Node('book')] class Book { #[Property('name', null)] #[Property('data-link', 'some-dummy-link')] public string $author; }
属性属性将为节点添加属性。它接受两个值:名称和值。如果值为null,它将从类属性中读取。我们还有对多个属性属性的支持,可以添加到多个类属性中。上面的示例将属性附加到父节点,因为Node属性未定义。在示例的情况下,我们会得到
<book name="George Orwell" data-link="some-dummy-link"/>
另一个带有Node属性的示例
#[Node('book')] class Book { #[Node('author')] #[Property('data-link', 'some-dummy-link')] public string $author; }
将产生
<book data-link="some-dummy-link"> <author>George Orwell</author> </book>
属性
关于性能的一些话
我设法在300毫秒内从50k个类生成XML,因此我相信它足够快。如果有人可以确认这一点,那会很好。