- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an array to SimpleXML in PHP?
We can solved the above problem using array_walk_recursive() function.array_walk_recursive() is an inbuilt PHP function. This function converts array to XML document where keys of the array are converted into values and values of the array are converted into the element of XML.
Let' demonstrate with a simple example.
Example
<?php $array = array ( 'name' => 'alex', 'empdept' => 'account', 'address' => array ( 'city' => 'michigan' ), ); //This function create a xml object with element root. $xml = new SimpleXMLElement(''); array_walk_recursive($array, array ($xml,'addChild')); print $xml->asXML(); ?>
Output
<?xml version="1.0"?> <root> <name> alex </name> <empdept> account </empdept> <city> michigan </city > </root>
Note
If errors message display like PHP Fatal error: Uncaught Error: Class 'SimpleXMLElement' not found in then simply install php-xml, php-simplexml packages.
Advertisements