Home >Backend Development >PHP Tutorial >How to Convert a PHP Array into a SimpleXML Object?
How to Convert an Array to a SimpleXML Object in PHP
In PHP, you can effortlessly convert an array to a SimpleXML object, a powerful tool for manipulating XML data. This technique enables you to easily create or modify XML documents programmatically.
Converting Arrays to SimpleXML
To convert an array to a SimpleXML object, you can use the following steps:
The array_to_xml Function
Here's the PHP code for the array_to_xml function:
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
Consider the following PHP array:
$data = array( 'total_stud' => 500, 0 => array( 'student' => array( 'id' => 1, 'name' => 'abc', 'address' => array( 'city' => 'Pune', 'zip' => '411006' ) ) ), 1 => array( 'student' => array( 'id' => 2, 'name' => 'xyz', 'address' => array( 'city' => 'Mumbai', 'zip' => '400906' ) ) ) );
Resultant XML
After converting the array using the array_to_xml function, the resulting XML would look like this:
<?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>
Conclusion
Converting arrays to SimpleXML objects in PHP allows you to work with XML data conveniently and efficiently. The asXML method provides the flexibility to save the generated XML to a file or output it directly, making this technique highly versatile and useful for web development, data processing, and many other applications.
The above is the detailed content of How to Convert a PHP Array into a SimpleXML Object?. For more information, please follow other related articles on the PHP Chinese website!