php

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.
 
[st_adsense]

<?php 
	$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.

<?php 
	function generateXML($data) {
		$name = $data['library'];
		$rowCount = count($data['book']);
		
		//create the XML document
		$xmlDoc = new DOMDocument();
		
		$root = $xmlDoc->appendChild($xmlDoc->createElement("book_info"));
		$root->appendChild($xmlDoc->createElement("title",$name));
		$root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
		$tabBooks = $root->appendChild($xmlDoc->createElement('rows'));
		
		foreach($data['book'] as $book){
			if(!empty($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';
		$xmlDoc->save($file_name);
		
		//returns the name of the xml file
		return $file_name;
	}
?>
[st_adsense]  
Then use the generateXML() function and transmit the multidimensional array to convert it to XML.

generateXML($arr);

Output:

<book_info>
	<title>MyLib</title>
	<totalRows>3</totalRows>
	<rows>
		<book>
			<title>Rear Window</title>
			<director>Alex Hitchcock</director>
			<year>1944</year>
		</book>
		<book>
			<title>Full Metal Jacket</title>
			<director>Thomas Kubrick</director>
			<year>1963</year>
		</book>
		<book>
			<title>Mean Streets</title>
			<director>Jean Scorsese</director>
			<year>1999</year>
		</book>
	</rows>
</book_info>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

Leave a Reply

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