PHP is a very powerful programming language that can easily convert arrays into XML format. Let’s learn how to convert an array to XML using PHP.
First, we need a PHP file containing array variables. We can use the following code to create a simple array:
$my_array = array( "name" => "John Doe", "age" => 30, "city" => "New York" );
Next, we can use PHP’s built-in function SimpleXMLElement()
to create an XML object:
$xml = new SimpleXMLElement('<root/>');
Then, use a loop to iterate through each array element and add it to the XML object:
foreach($my_array as $key => $value){ $xml->addChild($key, $value); }
In this example, we use the addChild()
function to add it to the XML object Add elements. The first parameter is the name of the element, and the second parameter is the value of the element.
Finally, we can use the asXML()
function to convert the XML object to a string and save it to a file:
$xml_string = $xml->asXML(); file_put_contents("my_xml_file.xml", $xml_string);
In this example, we use ## The #asXML() function converts an XML object to a string and uses the
file_put_contents() function to save the string to an XML file.
The above is the detailed content of How to convert array to XML using PHP. For more information, please follow other related articles on the PHP Chinese website!