lianhua/superxml

该软件包已被弃用,不再维护。未建议替代包。

一个简单的XML操作库

1.0.1 2020-06-15 09:15 UTC

This package is auto-updated.

Last update: 2023-05-29 01:40:30 UTC


README

一个简单的PHP XML操作库

Build Status BCH compliance License: GPL v3

概述

一个用于PHP中操作XML文件的简单库

兼容性

此库已在PHP 7.3及以上版本中进行测试

安装

只需在项目中使用composer

composer require lianhua/superxml

如果您不使用composer,克隆或下载此存储库,所有内容都在src目录中。

用法

打开XML文件

假设我们有一个以下XML文件

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
    </fruits>
    <vegetables>
        <vegetable>Carrot</vegetable>
    </vegetables>
</inventory>

您可以用新的SuperXML打开此文档

$xml = new SuperXML("/path/to/xml/file");

搜索节点

您可以通过XPath表达式搜索所有节点

$nodes = $xml->xpathQuery("/inventory/fruits/fruit"); // DOMNodeList with 'Apple' and 'Banana' nodes

评估表达式

您可以通过XPath表达式进行评估

$count = $xml->xpathEval("count(/inventory/fruits/fruit)"); // 2

创建节点

您可以使用父节点的XPath表达式创建一个节点

$xml->addChild("/inventory/fruits", "fruit", "Kiwi");

文档变为

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
        <fruit>Kiwi</fruit>
    </fruits>
    <vegetables>
        <vegetable>Carrot</vegetable>
    </vegetables>
</inventory>

删除节点

您可以删除一个节点

$xml->remove("/inventory/vegetables/vegetable");

文档变为

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
    </fruits>
    <vegetables>

    </vegetables>
</inventory>

替换值

您可以替换节点值

$xml->replaceValue("/inventory/vegetables/vegetable", "Potato");

文档变为

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
    </fruits>
    <vegetables>
        <vegetable>Potato</vegetable>
    </vegetables>
</inventory>

设置属性

您可以为节点设置属性

$xml->setAttribute("/document/vegetables/vegetable[.='Carrot']", "growIn", "soil");

文档变为

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
    </fruits>
    <vegetables>
        <vegetable growIn="soil">Carrot</vegetable>
    </vegetables>
</inventory>

删除属性

您可以删除属性,例如从最后的示例开始

$xml->removeAttribute("/document/vegetables/vegetable[.='Carrot']", "growIn", "soil");

文档变为

<inventory>
    <fruits>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
    </fruits>
    <vegetables>
        <vegetable>Carrot</vegetable>
    </vegetables>
</inventory>

自动保存

默认情况下,每次编辑文档时都会保存文档。为了避免这种情况,请将第二个构造函数参数设置为false

$xml = new SuperXML("/path/to/xml/file", false);