How to create XML in PHP

create XML in PHP
Code Snippet: Create XML in PHP This article explores how to create XML in PHP. Here’s a solution using SimpleXMLElement class. $products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80], ]; $root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><products/>'); foreach($products as $index => $subarray) { $product = $root->addChild('product'); //<product></product> $product->addAttribute('Id', $index); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) { $product->addChild($k, $v); //Adds name, price and availability. } } $root->asXML('products.xml'); That’s one obvious option, but that’s not the only one. We will see another class that represents DOM documents in PHP. So, stay tuned to learn something exciting today. Relevant Content: SimpleXMLElement in PHP The SimpleXMLElement class represents an XML element and defines…

read more