kiwilan/php-xml-reader

一个用于读取XML的PHP包,具有优秀的API。

1.0.11 2023-09-20 10:38 UTC

README

Banner with cards catalog picture in background and PHP XML Reader title

php version downloads license tests codecov

一个使用优秀API读取XML的PHP包,深受stackoverflow answer的启发。

关于

PHP原生支持使用SimpleXML读取XML文件,但这并不容易使用,也不够灵活。本包提供了一种简单灵活的API来以数组形式读取XML文件。

要求

  • PHP版本 >= 8.0

安装

您可以通过composer安装此包

composer require kiwilan/php-xml-reader

使用方法

您可以从路径或内容中读取XML。

  • mapContent: boolean 如果一个键只包含@content键,则只返回@content的值。默认:true
  • failOnError: boolean 如果XML无效,则抛出异常。默认:true
use KiwiLan\XmlReader\XmlReader;

$xml = XmlReader::make('path/to/file.xml', bool $mapContent = true, bool $failOnError = true);

方法

高级方法

基本使用

root获取多维度数组形式的XML(安全)。

$content = $xml->getContents();

基本使用。

$title = $content['metadata']['dc:title'] ?? null;

查找

查找键将返回包含title的键的第一个值(安全)。

$title = $xml->find('title', strict: false);

查找键将返回键为dc:title的第一个值(安全)

$dcTitle = $xml->find('dc:title');

查找键将返回包含dc:title的键并返回@content(安全)

$dcCreator = $xml->find('dc:creator', content: true);

查找键将返回包含dc:creator的键并返回@attributes(安全)

$dcCreator = $xml->find('dc:creator', attributes: true);

搜索

搜索将返回所有包含dc的值(安全)

$dc = $xml->search('dc');

提取

提取metadata键,如果未找到则返回null(安全)

$rootKey = $xml->extract('metadata');

提取metadatadc:title键(安全)

$subSubKey = $xml->extract(['metadata', 'dc:title']);

获取内容

如果您只想提取@content,可以使用parseContent()方法,如果您只想提取@attributes,可以使用parseAttributes()方法。

提取dc:title键并返回@content(安全)

$title = $xml->extract(['metadata', 'dc:title']);
$title = XmlReader::parseContent($title);

提取dc:creator键并返回@content(安全)

$creator = $xml->extract(['metadata', 'dc:creator']);
$creator = XmlReader::parseContent($creator);

提取dc:creator键并返回@attributes(安全)

$creatorAttributes = $xml->extract(['metadata', 'dc:creator']);
$creatorAttributes = XmlReader::parseAttributes($creatorAttributes);

测试

composer test

变更日志

有关最近更改的更多信息,请参阅CHANGELOG

鸣谢

  • spatiespatie/package-skeleton-php

许可证

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