Array Conversion to SimpleXML Tutorial in PHP
- 2021-11-13 06:57:29
- OfStack
The SimpleXML extension function provides a toolset for converting XML into objects. These objects handle ordinary property selectors and array iterators.
Example 1:
<?php
// Will php Array is converted to xml Code for the document
// Definition 1 Converts an array to xml The function of.
function arrayToXml($array, $rootElement = null, $xml = null) {
$_xml = $xml;
// If not $rootElement Is inserted $rootElement
if ($_xml === null) {
$_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
}
// Access all key-value pairs
foreach ($array as $k => $v) {
// If you have nested arrays
if (is_array($v)) {
// Calling functions of nested arrays
arrayToXml($v, $k, $_xml->addChild($k));
}
else {
$_xml->addChild($k, $v);
}
}
return $_xml->asXML();
}
// Create 1 Array for demonstration
$my_array = array (
'name' => 'GFG',
'subject' => 'CS',
// Create a nested array.
'contact_info' => array (
'city' => 'Noida',
'state' => 'UP',
'email' => '448199179@qq.com'
),
);
// Call arrayToxml Function and print the result
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>
You can use the array_walk_recursive () function to solve the above problem. This function converts an array to an xml document, where the key of the array is converted to a value and the value of the array is converted to an xml element.
Example 2:
<?php
// Will php Array is converted to xml Code for the document
// Create 1 Array of numbers
$my_array = array (
'a' => 'x',
'b' => 'y',
// creating nested array
'another_array' => array (
'c' => 'z',
),
);
// This function uses the root Element creation 1 A xml Object.
$xml = new SimpleXMLElement('<root/>');
// This function re-adds the array elements to the xml In the document
array_walk_recursive($my_array, array ($xml, 'addChild'));
// This function prints xml Documents.
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 found in in/home/6bc5567266b 35ae 33EN 76d 84307ES45ES5bdc 78. php: 24,
Then just install the php-xml, php-simplexml packages.