aircury / xml
使用 PHP 轻松处理 XML
dev-master / 1.0.x-dev
2020-07-17 06:16 UTC
Requires
- aircury/collection: dev-master
Requires (Dev)
- phpunit/phpunit: ^8.2
This package is auto-updated.
Last update: 2024-09-17 16:50:31 UTC
README
XML
使用 PHP 轻松处理 XML
安装
下载库
此库使用 Composer。您需要在您的机器上安装它。有关说明,请参阅 Composer。这里我们假设您已全局安装了 Composer。
$ composer require aircury/xml
文档
类文档
Xml
parseString(string $xmlString): Node
给定一个 xml 字符串,将其解析为一个 Node 对象。parseFile(string $path): Node
给定一个路径,将其文件解析为一个 Node 对象。dump(Node $node): string
给定任何 Node,将其转换为 xml 字符串。
Node
Node 是基类。
如果您想设置一些属性,有以下三种选择
- 您可以将它们传递给构造函数。例如
new Node('pizza', ['crust' => 'classic'])
- Node 实现 \ArrayAccess,因此您可以使用
$pizza['crust']
来设置或读取属性。 - Node 有一个公开属性名为
attributes
,因此您可以直接访问它们。$pizza->attributes['crust'] = 'classic';
NodeCollection
它是一组节点。
方法
indexByAttribute(string $attribute): NodeCollection
给定一个属性,将集合按该属性索引getNamedChildren(string $childName, array $attributes = [], bool $createIfMissing = false): NodeCollection
获取子节点的子集,通过$attributes
过滤。如果$createIfMissing
被传递,它将确保在没有匹配项时创建它。getNamedChild(string $childName, array $attributes = [], bool $createIfMissing = true): Node
与getNamedChildren
相同,但期望只有一个匹配。
示例
$pizza = new Node('pizza'); // Create a new 'pizza' node. $peperoni = new Node('ingredient', ['name' => 'peperoni', 'spicy' => 'true']); $slice = new Node('slice'); $pizza->addChild($peperoni); $pizza->addChild(new Node('ingredient', ['name' => 'cheese', 'type' => 'cheddar'])); $pizza->addChild(new Node('ingredient', ['name' => 'cheese', 'type' => 'camembert'])); $pizza->addChild($slice); $pizza['crust'] = 'classic'; // Set the crust attribute of the pizza node unset($peperoni['spicy']); // Remove an attirbute from the peperoni ingredient node if (isset($peperoni['spicy'])) { // ... } // Get all the 'ingredient' nodes of the 'pizza' $ingredients = $pizza->namedChildren['ingredient']; // Access the peperoni ingredient $pizza->namedChildren['ingredient'][0]; // If you want to access them by any of the attributes, you can index them by that attribute $pizza->indexByAttribute('ingredient', 'name'); $pizza->namedChildren['ingredient']['peperoni']; // If you want to filter the child nodes by an attribute, you can use `getNamedChildren` $cheeses = $pizza->getNamedChildren('ingredient', ['name' => 'cheese']); // Will return a NodeCollection with two elements // By default, if the children that you are after don't exist, it will create them. if you don't want them to be created // pass the third argument as false $emptyCollection = $pizza->getNamedChildren('ingredient', ['name' => 'mushroom'], false); // If there is only one child, you can also use `getNamedChild` $slice = $pizza->getNamedChild('slice');
许可证
此软件根据 MIT 许可证 发布。