PHP – Convert Multidimensional Array to XML file

In this tutorial, we are going to see how to convert a multidimensional array into an XML file with PHP.

To convert the multidimensional array into an xml file, create an XML file and use appendChild() and createElement() function to append an array element into an XML file.

Start by creating a multidimensional array to convert this array to XML file format.

	$arr = array(
			'library'=> 'MyLib',
			'book'=> array(
				'0' => array(
					"title" => "Rear Window",
					"director" => "Alex Hitchcock",
					"year" => 1944
				'1' => array(
					"title" => "Full Metal Jacket",
					"director" => "Thomas Kubrick",
					"year" => 1963
				'2' => array(
					"title" => "Mean Streets",
					"director" => "Jean Scorsese",
					"year" => 1999

Now you have to create a function called generatXML() to generate the XML.

	function generateXML($data) {
		$name = $data['library'];
		$rowCount = count($data['book']);
		//create the XML document
		$xmlDoc = new DOMDocument();
		$root = $xmlDoc->appendChild($xmlDoc->createElement("book_info"));
		$tabBooks = $root->appendChild($xmlDoc->createElement('rows'));
		foreach($data['book'] as $book){
				$tabBook = $tabBooks->appendChild($xmlDoc->createElement('book'));
				foreach($book as $key=>$val){
					$tabBook->appendChild($xmlDoc->createElement($key, $val));
		header("Content-Type: text/plain");
		//format the output
		$xmlDoc->formatOutput = true;
		//save the XML file
		$file_name = str_replace(' ', '_',$name).'.xml';
		//returns the name of the xml file
		return $file_name;
Then use the generateXML() function and transmit the multidimensional array to convert it to XML.



			<title>Rear Window</title>
			<director>Alex Hitchcock</director>
			<title>Full Metal Jacket</title>
			<director>Thomas Kubrick</director>
			<title>Mean Streets</title>
			<director>Jean Scorsese</director>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *