PHP 

The example, convert csv to xml using PHP , shows conversion of csv data to xml data. As the title suggests to convert csv to xml using PHP, so we will convert either csv file to xml file or csv string to xml string. When we convert csv string to xml string you will see the output on the browser and when we convert csv file to xml file then you will see the xml document saved into a file on the physical drive location. So here in this example we will see both examples that may help you to choose the example according to your situations.

People working with different types of data may come across the problem that they need to convert between different data formats. Comma Separated Values (CSV) and the Extensible Markup Language (XML) are the most widely used formats for data, and conversion between these two formats needs often to be accomplished. Especially to XML, because this format is very well supported by modern applications, and is very well suited for further data manipulation and customization.

There are many tools available online to convert csv to xml but it is very often quite hard to find the appropriate methods that suits one’s particular needs. So here we are going to write our own program to convert csv to xml using php language. Therefore you don’t need to be dependent on any such particular tool to convert csv to xml document.

You may also like to read:

How to convert XML to CSV using PHP

Read from and write to CSV file using PHP

So let’s get started on the implementation part.

Prerequisites

Knowledge of PHP, CSV and XML

Softwares

PHP 7

XAMPP on Windows

Example

Please write below PHP code to convert csv to xml string. Here we will get the csv string as an input and show the xml string output on the browser.

First we write below php function in order to convert csv to xml string

//function to convert csv to xml string
function convertCsvToXmlString($csv_string) {
	// split rows into lines
	$lines = explode(PHP_EOL, $csv_string);
	
	// retrieve headers
	$headers = explode(',', array_shift($lines));
	
	// Create a new dom document with pretty formatting
	$doc  = new DomDocument();
	$doc->formatOutput   = true;
	
	// Add a root node to the document
	$root = $doc->createElement('policies');
	$root = $doc->appendChild($root);
	
	// Loop through each row creating a <policy> node with the correct data
	foreach ($lines as $line)
	{
		$row = str_getcsv($line);
		$container = $doc->createElement('policy');
		
		foreach($headers as $i => $header)
		{
			$child = $doc->createElement($header);
			$child = $container->appendChild($child);
			$value = $doc->createTextNode($row[$i]);
			$value = $child->appendChild($value);
		}
		$root->appendChild($container);
	}
	
	$strxml = $doc->saveXML();
	
	echo $strxml;
}

In the above function, we retrieve all lines into $lines variable using the delimiter PHP_EOL (End Of Line delimiter).

The next line retrieves all headers from csv string into $headers variable.

Next we want to produce the xml string with pretty format. Then we create root node policies for xml string. You may give other name as well as per your choice or requirement.

Then we iterate through each line and create node policy under root node policies. For each policy node we create nodes with headers and set the value for each node under policy node.

Now we will test the above function using php code. We assign csv string with sample data into a variable as shown below:

$csv_string ='policyID,statecode,county,eq_site_limit,hu_site_limit,fl_site_limit,fr_site_limit,tiv_2011,tiv_2012,eq_site_deductible,hu_site_deductible,fl_site_deductible,fr_site_deductible,point_latitude,point_longitude,line,construction,point_granularity
119736,FL,CLAY COUNTY,498960,498960,498960,498960,498960,792148.9,0,9979.2,0,0,30.102261,-81.711777,Residential,Masonry,1
448094,FL,CLAY COUNTY,1322376.3,1322376.3,1322376.3,1322376.3,1322376.3,1438163.57,0,0,0,0,30.063936,-81.707664,Residential,Masonry,3
206893,FL,CLAY COUNTY,190724.4,190724.4,190724.4,190724.4,190724.4,192476.78,0,0,0,0,30.089579,-81.700455,Residential,Wood,1
333743,FL,CLAY COUNTY,0,79520.76,0,0,79520.76,86854.48,0,0,0,0,30.063236,-81.707703,Residential,Wood,3
172534,FL,CLAY COUNTY,0,254281.5,0,254281.5,254281.5,246144.49,0,0,0,0,30.060614,-81.702675,Residential,Wood,1
785275,FL,CLAY COUNTY,0,515035.62,0,0,515035.62,884419.17,0,0,0,0,30.063236,-81.707703,Residential,Masonry,3
995932,FL,CLAY COUNTY,0,19260000,0,0,19260000,20610000,0,0,0,0,30.102226,-81.713882,Commercial,Reinforced Concrete,1
223488,FL,CLAY COUNTY,328500,328500,328500,328500,328500,348374.25,0,16425,0,0,30.102217,-81.707146,Residential,Wood,1
433512,FL,CLAY COUNTY,315000,315000,315000,315000,315000,265821.57,0,15750,0,0,30.118774,-81.704613,Residential,Wood,1';

Then we set the header with Content-Type because we want to show the xml data on browser.

header('Content-type: text/xml');

Next we call the above function

convertCsvToXmlString($csv_string);

Now when you run the php file, you should see xml output on the browser as shown in the below image.

convert csv to xml using php

So we have seen how to convert csv to xml using php. Here we have used csv string. Next we will see how to read csv file and produce xml file as an output.

You may also like to read Read from and write to csv file using php

So create below php function that will convert csv to xml file.

function convertCsvToXmlFile($input_file, $output_file) {
	// Open csv file for reading
	$inputFile  = fopen($input_file, 'rt');
	
	// Get the headers of the file
	$headers = fgetcsv($inputFile);
	
	// Create a new dom document with pretty formatting
	$doc  = new DomDocument();
	$doc->formatOutput   = true;
	
	// Add a root node to the document
	$root = $doc->createElement('policies');
	$root = $doc->appendChild($root);
	
	// Loop through each row creating a <policy> node with the correct data
	while (($row = fgetcsv($inputFile)) !== FALSE)
	{
		$container = $doc->createElement('policy');
		
		foreach($headers as $i => $header)
		{
			$child = $doc->createElement($header);
			$child = $container->appendChild($child);
			$value = $doc->createTextNode($row[$i]);
			$value = $child->appendChild($value);
		}
		$root->appendChild($container);
	}
	
	$strxml = $doc->saveXML();
	
	$handle = fopen($output_file, "w");
	fwrite($handle, $strxml);
	fclose($handle);
}

In the above function the $input_file refers to the complete csv file path with file name. The $output_file refers to the complete xml output file path with file name.

First we read the csv file in text mode (rt : r -> reading, t -> text mode). Then we retrieve headers from the csv file into $headers variable.

Then the logic for creating root node and sub-nodes are same.

Finally we save the xml output into an xml file. The output file is opened in write mode (w).

Now we will test the above function using the below php code

convertCsvToXmlFile("C:\Users\Desktop\FL_insurance.csv", "C:\Users\Desktop\FL_insurance.xml");

In the above code FL_insurance.csv is the input file and FL_insurance.xml is the output file.

The content is same as we had seen input csv string. You may download the file here FL_insurance. You can also check the output file here FL_insurance.

The final output in the xml file should be similar to below

convert csv to xml using php

Hope you have got idea how to convert csv to xml using php. You have also learnt how to read csv file and write to xml file.

You may also like to read:

How to convert XML to CSV using PHP

Read from and write to CSV file using PHP

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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