Project Icon

array-to-xml

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

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

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

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

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

Project Cover

稿定AI

稿定设计 是一个多功能的在线设计和创意平台,提供广泛的设计工具和资源,以满足不同用户的需求。从专业的图形设计师到普通用户,无论是进行图片处理、智能抠图、H5页面制作还是视频剪辑,稿定设计都能提供简单、高效的解决方案。该平台以其用户友好的界面和强大的功能集合,帮助用户轻松实现创意设计。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号