How to Convert CSV to XML using PHP

Introduction

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 I will convert either csv file to xml file or csv string to xml string. When I convert csv string to xml string you will see the output on the browser and when I 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, you 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 I am 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.

Related Posts:

So let’s get started on the implementation part.

Prerequisites

PHP 7.3.5 – 7.4.3, Apache 2.4 HTTP Server

Project Directory

It’s assumed that you have already setup PHP and Apache HTTP Server in your operating system.

Now I will create a project root directory called php-csv-xml anywhere in the system and all files will be kept under this root folder.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

CSV to XML String Conversion

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

//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, I 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 I want to produce the xml string with pretty format. Then I create root node policies for xml string. You may give other name as well, as per your choice or requirement.

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

Testing CSV to XML String Conversion

Now I will test the above function using php code. I 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 I set the header with Content-Type because I want to show the xml data on browser.

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

Next I call the above function to convert CSV string to XML string:

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 you have seen how to convert csv to xml using php. Here I have used csv string.

CSV to XML File Conversion

Next you 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 I read the csv file in text mode (rt : r -> reading, t -> text mode). Then I retrieve headers from the csv file into $headers variable.

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

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

Now I will test the above function using the below php code:

convertCsvToXmlFile("FL_insurance.csv", "FL_insurance.xml");

In the above code FL_insurance.csv is the input file and FL_insurance.xml is the output file. Note that the file FL_insurance.csv is kept in the same directory where your PHP script is kept.

Testing CSV to XML File Conversion

The content is same as you had seen input csv string.

You may download the input and output files from the link below:

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.

Related Posts:

Source Code

Download

Leave a Comment