Home >Backend Development >PHP Tutorial >How to Convert PHP Arrays to SimpleXML Objects?

How to Convert PHP Arrays to SimpleXML Objects?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 02:52:08862browse

How to Convert PHP Arrays to SimpleXML Objects?

Converting Arrays to SimpleXML Objects in PHP

In PHP, converting arrays to SimpleXML objects can be a convenient way to manipulate XML data.

Solution

The following code snippet provides a solution to the problem of converting an array to a SimpleXML object:

// Array to be converted
$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
            )
        )
    )
);

// Create a SimpleXMLElement object
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><student_info></student_info>');

// Function to convert array to XML
function array_to_xml($data, &$xml_data) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            if (is_numeric($key)) {
                $key = 'item' . $key; // Handle numeric keys
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key", htmlspecialchars("$value"));
        }
    }
}

// Convert array to XML
array_to_xml($data, $xml_data);

// Save the generated XML file
$result = $xml_data->asXML('/file/path/name.xml');

This code defines a function called array_to_xml that recursively iterates through the array and adds SimpleXMLElement nodes to the provided $xml_data object. It handles numeric array keys by adding a prefix of item. The htmlspecialchars function is used to escape any special characters in the array values to ensure proper XML formation. Finally, the generated XML is saved to a file using asXML.

The above is the detailed content of How to Convert PHP Arrays to SimpleXML Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn