array-to-xml

array-to-xml

将PHP数组转换为XML的高效开源库

array-to-xml是一个用于将PHP数组转换为XML字符串的开源库。该库支持自定义根元素、添加属性、CDATA包装和处理多维数组。它还提供XML美化、移除XML声明和添加处理指令等功能,增强了XML生成的灵活性。array-to-xml由Spatie公司开发,以简洁的API和全面的功能著称,是PHP开发者进行数组到XML转换的实用工具。

ArrayToXmlPHPXML转换数组处理数据序列化Github开源项目

Convert an array to xml

Latest Version Software License Tests Total Downloads

This package provides a very simple class to convert an array to an xml string.

Support us

<img src="https://github-ads.s3.eu-central-1.amazonaws.com/array-to-xml.jpg?t=1" width="419px" />

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Install

You can install this package via composer.

composer require spatie/array-to-xml

Usage

use Spatie\ArrayToXml\ArrayToXml; ... $array = [ 'Good guy' => [ 'name' => 'Luke Skywalker', 'weapon' => 'Lightsaber' ], 'Bad guy' => [ 'name' => 'Sauron', 'weapon' => 'Evil Eye' ] ]; $result = ArrayToXml::convert($array);

After running this piece of code $result will contain:

<?xml version="1.0"?> <root> <Good_guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </Good_guy> <Bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </Bad_guy> </root>

Setting the name of the root element

Optionally you can set the name of the rootElement by passing it as the second argument. If you don't specify this argument (or set it to an empty string) "root" will be used.

$result = ArrayToXml::convert($array, 'customrootname');

Handling key names

By default all spaces in the key names of your array will be converted to underscores. If you want to opt out of this behaviour you can set the third argument to false. We'll leave all keynames alone.

$result = ArrayToXml::convert($array, 'customrootname', false);

Adding attributes

You can use a key named _attributes to add attributes to a node, and _value to specify the value.

$array = [ 'Good guy' => [ '_attributes' => ['attr1' => 'value'], 'name' => 'Luke Skywalker', 'weapon' => 'Lightsaber' ], 'Bad guy' => [ 'name' => 'Sauron', 'weapon' => 'Evil Eye' ], 'The survivor' => [ '_attributes' => ['house'=>'Hogwarts'], '_value' => 'Harry Potter' ] ]; $result = ArrayToXml::convert($array);

This code will result in:

<?xml version="1.0"?> <root> <Good_guy attr1="value"> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </Good_guy> <Bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </Bad_guy> <The_survivor house="Hogwarts"> Harry Potter </The_survivor> </root>

Note, that the value of the _value field must be a string. (More)

Using reserved characters

It is also possible to wrap the value of a node into a CDATA section. This allows you to use reserved characters.

$array = [ 'Good guy' => [ 'name' => [ '_cdata' => '<h1>Luke Skywalker</h1>' ], 'weapon' => 'Lightsaber' ], 'Bad guy' => [ 'name' => '<h1>Sauron</h1>', 'weapon' => 'Evil Eye' ] ]; $result = ArrayToXml::convert($array);

This code will result in:

<?xml version="1.0"?> <root> <Good_guy> <name><![CDATA[<h1>Luke Skywalker</h1>]]></name> <weapon>Lightsaber</weapon> </Good_guy> <Bad_guy> <name>&lt;h1&gt;Sauron&lt;/h1&gt;</name> <weapon>Evil Eye</weapon> </Bad_guy> </root>

If your input contains something that cannot be parsed a DOMException will be thrown.

Customize the XML declaration

You could specify specific values in for:

  • encoding as the fourth argument (string)
  • version as the fifth argument (string)
  • DOM properties as the sixth argument (array)
  • standalone as seventh argument (boolean)
$result = ArrayToXml::convert($array, [], true, 'UTF-8', '1.1', [], true);

This will result in:

<?xml version="1.1" encoding="UTF-8" standalone="yes"?>

Adding attributes to the root element

To add attributes to the root element provide an array with an _attributes key as the second argument. The root element name can then be set using the rootElementName key.

$result = ArrayToXml::convert($array, [    'rootElementName' => 'helloyouluckypeople', '_attributes' => [ 'xmlns' => 'https://github.com/spatie/array-to-xml', ], ], true, 'UTF-8');

Using a multi-dimensional array

Use a multi-dimensional array to create a collection of elements.

$array = [ 'Good guys' => [ 'Guy' => [ ['name' => 'Luke Skywalker', 'weapon' => 'Lightsaber'], ['name' => 'Captain America', 'weapon' => 'Shield'], ], ], 'Bad guys' => [ 'Guy' => [ ['name' => 'Sauron', 'weapon' => 'Evil Eye'], ['name' => 'Darth Vader', 'weapon' => 'Lightsaber'], ], ], ];

This will result in:

<?xml version="1.0" encoding="UTF-8"?> <helloyouluckypeople xmlns="https://github.com/spatie/array-to-xml"> <Good_guys> <Guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </Guy> <Guy> <name>Captain America</name> <weapon>Shield</weapon> </Guy> </Good_guys> <Bad_guys> <Guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </Guy> <Guy> <name>Darth Vader</name> <weapon>Lightsaber</weapon> </Guy> </Bad_guys> </helloyouluckypeople>

Using Closure values

The package can use Closure values:

$users = [ [ 'name' => 'one', 'age' => 10, ], [ 'name' => 'two', 'age' => 12, ], ]; $array = [ 'users' => function () use ($users) { $new_users = []; foreach ($users as $user) { $new_users[] = array_merge( $user, [ 'double_age' => $user['age'] * 2, ] ); } return $new_users; }, ]; ArrayToXml::convert($array)

This will result in:

<?xml version="1.0"?> <root> <users> <name>one</name> <age>10</age> <double_age>20</double_age> </users> <users> <name>two</name> <age>12</age> <double_age>24</double_age> </users> </root>

Handling numeric keys

The package can also can handle numeric keys:

$array = [ 100 => [ 'name' => 'Vladimir', 'nickname' => 'greeflas', ], 200 => [ 'name' => 'Marina', 'nickname' => 'estacet', ], ]; $result = ArrayToXml::convert(['__numeric' => $array]);

This will result in:

<?xml version="1.0" encoding="UTF-8"?> <root> <numeric_100> <name>Vladimir</name> <nickname>greeflas</nickname> </numeric_100> <numeric_200> <name>Marina</name> <nickname>estacet</nickname> </numeric_200> </root>

You can change key prefix with setter method called setNumericTagNamePrefix().

Using custom keys

The package can also can handle custom keys:

$array = [ '__custom:custom-key:1' => [ 'name' => 'Vladimir', 'nickname' => 'greeflas', ], '__custom:custom-key:2' => [ 'name' => 'Marina', 'nickname' => 'estacet', 'tags' => [ '__custom:tag:1' => 'first-tag', '__custom:tag:2' => 'second-tag', ] ], ]; $result = ArrayToXml::convert($array);

This will result in:

<?xml version="1.0" encoding="UTF-8"?> <root> <custom-key> <name>Vladimir</name> <nickname>greeflas</nickname> </custom-key> <custom-key> <name>Marina</name> <nickname>estacet</nickname> <tags> <tag>first-tag</tag> <tag>second-tag</tag> </tags> </custom-key> </root>

A custom key contains three, colon-separated parts: "__custom:[custom-tag]:[unique-string]".

  • "__custom"
    • The key always starts with "__custom".
  • [custom-tag]
    • The string to be rendered as the XML tag.
  • [unique-string]
    • A unique string that avoids overwriting of duplicate keys in PHP arrays.

a colon character can be included within the custom-tag portion by escaping it with a backslash:

$array = [ '__custom:ns\\:custom-key:1' => [ 'name' => 'Vladimir', 'nickname' => 'greeflas', ], '__custom:ns\\:custom-key:2' => [ 'name' => 'Marina', 'nickname' => 'estacet', 'tags' => [ '__custom:ns\\:tag:1' => 'first-tag', '__custom:ns\\:tag:2' => 'second-tag', ] ], ];

This will result in:

<?xml version="1.0" encoding="UTF-8"?> <root> <ns:custom-key> <name>Vladimir</name> <nickname>greeflas</nickname> </ns:custom-key> <ns:custom-key> <name>Marina</name> <nickname>estacet</nickname> <tags> <ns:tag>first-tag</ns:tag> <ns:tag>second-tag</ns:tag> </tags> </ns:custom-key> </root>

Setting DOMDocument properties

To set properties of the internal DOMDocument object just pass an array consisting of keys and values. For a full list of valid properties consult https://www.php.net/manual/en/class.domdocument.php.

You can use the constructor to set DOMDocument properties.

$result = ArrayToXml::convert( $array, $rootElement, $replaceSpacesByUnderScoresInKeyNames, $xmlEncoding, $xmlVersion, ['formatOutput' => true] );

Alternatively you can use setDomProperties

$arrayToXml = new ArrayToXml($array); $arrayToXml->setDomProperties(['formatOutput' => true]); $result = $arrayToXml->toXml();

XML Prettification

Call $arrayToXml->prettify() method on ArrayToXml to set XML in pretty form.

Example:

$array = [ 'Good guy' => [ 'name' => 'Luke Skywalker', 'weapon' => 'Lightsaber' ], 'Bad guy' => [ 'name' => 'Sauron', 'weapon' => 'Evil Eye' ] ]; $arrayToXml = new ArrayToXml($array);

With prettification:

$arrayToXml->prettify()->toXml();

will result in:

<?xml version="1.0"?> <root> <Good_guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </Good_guy> <Bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </Bad_guy> </root>

Without prettification:

$arrayToXml->toXml();

will result in:

<?xml version="1.0"?> <root><Good_guy><name>Luke Skywalker</name><weapon>Lightsaber</weapon></Good_guy><Bad_guy><name>Sauron</name><weapon>Evil Eye</weapon></Bad_guy></root>

Dropping XML declaration

Call $arrayToXml->dropXmlDeclaration() method on ArrayToXml object to omit default XML declaration on top of the generated XML.

Example:

$root = [ 'rootElementName' => 'soap:Envelope', '_attributes' => [ 'xmlns:soap' => 'http://www.w3.org/2003/05/soap-envelope/', ], ]; $array = [ 'soap:Header' => [], 'soap:Body' => [ 'soap:key' => 'soap:value', ], ]; $arrayToXml = new ArrayToXml($array, $root); $result = $arrayToXml->dropXmlDeclaration()->toXml();

This will result in:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"><soap:Header/><soap:Body><soap:key>soap:value</soap:key></soap:Body></soap:Envelope>

Adding processing instructions

Call $arrayToXml->addProcessingInstruction($target, $data) method on ArrayToXml object to prepend a processing instruction before the root element.

Example:

$arrayToXml = new ArrayToXml($array); $arrayToXml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"'); $result = $arrayToXml->toXml();

This will result in:

<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="base.xsl"?> <root><Good_guy><name>Luke Skywalker</name><weapon>Lightsaber</weapon></Good_guy><Bad_guy><name>Sauron</name><weapon>Evil Eye</weapon></Bad_guy></root>

Testing

vendor/bin/phpunit

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多