Home >Backend Development >PHP Tutorial >How to convert array to SimpleXML in PHP
Many times it is necessary to store data as XML format into a database or file for later use. To meet this requirement, the data needs to be converted to XML and the XML file saved.
#SimpleXML extension functions provide a toolset for converting XML into objects. These objects handle ordinary property selectors and array iterators.
Example 1:
<?php // 将php数组转换为xml文档的代码 //定义一个将数组转换成xml的函数。 function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; // 如果没有$rootElement,则插入$rootElement if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); } // 访问所有键值对 foreach ($array as $k => $v) { // 如果有嵌套数组 if (is_array($v)) { // 调用嵌套数组的函数 arrayToXml($v, $k, $_xml->addChild($k)); } else { $_xml->addChild($k, $v); } } return $_xml->asXML(); } // 创建一个用于演示的数组 $my_array = array ( 'name' => 'GFG', 'subject' => 'CS', // 创建嵌套数组。 'contact_info' => array ( 'city' => 'Noida', 'state' => 'UP', 'email' => '448199179@qq.com' ), ); // 调用arrayToxml函数并打印结果 echo arrayToXml($my_array); ?>
Output:
<?xml version="1.0"?> <root> <name> GFG </name> <subject> CS </subject> <contact_info > <city > Noida < /city > <state > UP < /state > <email > 448199179@qq.com </email> <contact_info> <root>
The above problem can be solved using the array_walk_recursive() function. This function converts an array into an xml document, where the keys of the array are converted into values and the values of the array are converted into elements of xml.
Example 2:
<?php // 将php数组转换为xml文档的代码 //创建一个数组 $my_array = array ( 'a' => 'x', 'b' => 'y', // creating nested array 'another_array' => array ( 'c' => 'z', ), ); // 这个函数使用root元素创建一个xml对象。 $xml = new SimpleXMLElement('<root/>'); // 这个函数重新将数组元素添加到xml文档中 array_walk_recursive($my_array, array ($xml, 'addChild')); // 这个函数打印xml文档。 print $xml->asXML(); ?>
Output:
<?xml version =“1.0”?> <root> <x> a </ x> <y> b </ y> <z> c </ z> </ root>
Note:
If the system generates an error type :
PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement’ not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 ,
Then just install the php-xml, php-simplexml packages.
This article is about the method of converting arrays to SimpleXML in PHP. I hope it will be helpful to friends in need!
The above is the detailed content of How to convert array to SimpleXML in PHP. For more information, please follow other related articles on the PHP Chinese website!