Converting Arrays to SimpleXML in PHP
When working with XML data in PHP, it can be necessary to convert arrays into SimpleXML objects to facilitate processing and manipulation.
Function for Array to XML Conversion
Here is a PHP function that can be used to convert multi-dimensional arrays to SimpleXML objects:
function array_to_xml( $data, &$xml_data ) { foreach( $data as $key => $value ) { if( is_array($value) ) { if( is_numeric($key) ){ $key = 'item'.$key; //dealing with <0/>..<n/> issues } $subnode = $xml_data->addChild($key); array_to_xml($value, $subnode); } else { $xml_data->addChild("$key",htmlspecialchars("$value")); } } }
Example Usage
Consider the following array:
$data = array('total_stud' => 500, 'student' => array( 0 => array( 'id' => 1, 'name' => 'abc', 'address' => array( 'city' => 'Pune', 'zip' => '411006' ) ), 1 => array( 'id' => 2, 'name' => 'xyz', 'address' => array( 'city' => 'Mumbai', 'zip' => '400906' ) ) ) );
To convert this array to XML, you can create a SimpleXMLElement object:
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><student_info></student_info>');
Then, call the array_to_xml function:
array_to_xml($data, $xml_data);
This will generate the following XML:
<?xml version="1.0"?> <student_info> <total_stud>500</total_stud> <student> <id>1</id> <name>abc</name> <address> <city>Pune</city> <zip>411006</zip> </address> </student> <student> <id>1</id> <name>abc</name> <address> <city>Mumbai</city> <zip>400906</zip> </address> </student> </student_info>
You can then save or process the generated XML as needed.
The above is the detailed content of How can I efficiently convert a multi-dimensional PHP array into a SimpleXML object?. For more information, please follow other related articles on the PHP Chinese website!