Converting XML to CSV with PHP

Using PHP to convert XML to CSV is fairly easy, at least in the situations I've encountered so far. In my case, it would save me significant work if I could simply convert structured XML data into CSV data. Typically, I want to convert only the data in a particular xpath of the original XML document. The PHP function below will load an XML file and convert the elements in the specified xpath to simple csv data.

<?php

echo xml2csv('import.xml', '/Some/Path');

// ----------
// xml2csv
// -----
function xml2csv($xmlFile, $xPath) {

	// Load the XML file
	$xml = simplexml_load_file($xmlFile);

	// Jump to the specified xpath
	$path = $xml->xpath($xPath);

	// Loop through the specified xpath
	foreach($path as $item) {
	
		// Loop through the elements in this xpath
		foreach($item as $key => $value) {
		
			$csvData .= '"' . trim($value) . '"' . ',';
		
		}
		
		// Trim off the extra comma
		$csvData = trim($csvData, ',');
		
		// Add an LF
		$csvData .= "\n";
	
	}
	
	// Return the CSV data
	return $csvData;
	
}

?>
comments powered by Disqus
php/converting_xml_to_csv_with_php.txt · Last modified: 2020/06/01 22:53 (external edit)