decodelabs/exemplar

强大的XML工具

v0.4.2 2024-08-21 23:11 UTC

This package is auto-updated.

Last update: 2024-09-04 21:05:42 UTC


README

PHP from Packagist Latest Version Total Downloads GitHub Workflow Status PHPStan License

PHP的强大XML工具。

Exemplar提供了一套详尽且直观的接口,用于读取、写入和操作XML文档和片段。

DecodeLabs 博客 上获取新闻和更新。

安装

composer require decodelabs/exemplar

使用方法

读取与操作

使用PHP中可用的DOM功能,通过一个综合的界面访问和操作XML文件

use DecodeLabs\Exemplar\Element as XmlElement;

$element = XmlElement::fromFile('/path/to/my/file.xml');

if($element->hasAttribute('old')) {
    $element->removeAttribute('old');
}

$element->setAttribute('new', 'value');

foreach($element->scanChildrenOfType('section') as $sectTag) {
    $inner = $sectTag->getFirstChildOfType('title');
    $sectTag->removeChild($inner);

    // Flatten to plain text
    echo $sectTag->getComposedTextContent();
}

file_put_contents('newfile.xml', (string)$element);

查看完整的接口,请参见 Element.php

写入

使用PHP的XML Writer的完整功能包装程序生成XML输出

use DecodeLabs\Exemplar\Writer as XmlWriter;

$writer = new XmlWriter();
$writer->writeHeader();

$writer->{'ns:section[ns:attr1=value].test'}(function ($writer) {
    $writer->{'title#main'}('This is a title');

    $writer->{'@body'}('This is an element with content wrapped in CDATA tags.');
    $writer->writeCData('This is plain CDATA');
});

echo $writer;

这创建了

<?xml version="1.0" encoding="UTF-8"?>
<ns:section ns:attr1="value" class="test">
    <title id="main">This is a title</title>
    <body><![CDATA[This is an element with content wrapped in CDATA tags.]]></body>
<![CDATA[This is plain CDATA]]></ns:section>

查看完整的接口,请参见 Writer.php

许可

Exemplar采用MIT许可证。有关完整的许可证文本,请参阅 LICENSE