Convert CSV file to XML with PHP

Pleabledamrah

New Member
I have researched for an answer and mainly with the help of answers in this question Convert Tab delimited text file to XML, pieced together the following script to read a CSV file line by line and then convert the results to an XML file.The CSV file has lines with three or more cells in this manner:John Doe [email protected] 06/07/2012 01:45When ran in the Interactive PHP shell, the following script ignores the first line of the file and spits out everything, from two lines at at time, inside the first xml tag:\[code\]<?phperror_reporting(E_ALL | E_STRICT);ini_set('display_errors', true);ini_set('auto_detect_line_endings', true);$xmlWriter = new XMLWriter();$xmlWriter->openUri('/path/to/destination.xml');$xmlWriter->setIndent(true);$xmlWriter->startDocument('1.0', 'UTF-8');$xmlWriter->startElement('root');$tsvFile = new SplFileObject('/path/to/destination.csv');$tsvFile->setFlags(SplFileObject::READ_CSV);$tsvFile->setCsvControl("\t");foreach ($tsvFile as $line => $row) {if($line > 0 && $line !== ' ') { $xmlWriter->startElement('item'); $xmlWriter->writeElement('name', $row[0]); $xmlWriter->writeElement('email', $row[1]); $xmlWriter->writeElement('date', $row[2]); $xmlWriter->endElement(); }}$xmlWriter->endElement();$xmlWriter->endDocument(); ?>\[/code\]To resolve this, I tried the solution here: tab-delimited string to XML with PHPThe following is the modified script:\[code\]<?phperror_reporting(E_ALL | E_STRICT);ini_set('display_errors', true);ini_set('auto_detect_line_endings', true);$xmlWriter = new XMLWriter();$xmlWriter->openUri('/path/to/destination.xml');$xmlWriter->setIndent(true);$xmlWriter->startDocument('1.0', 'UTF-8');$xmlWriter->startElement('root');$tsvFile = new SplFileObject('/path/to/destination.csv');$tsvFile->setFlags(SplFileObject::READ_CSV);$tsvFile->setCsvControl("\t");$lines = explode("\n", $tsvFile);$tsvData = http://stackoverflow.com/questions/11364483/array();foreach ($lines as $line ) { if($line > 0 ) { $tsvData[] = str_getcsv($line,"\t"); $tsvData[] = str_getcsv($line, "\t"); foreach ($tsvData as $row) { $xmlWriter->writeElement('name', $row[0]); $xmlWriter->writeElement('email', $row[1]); $xmlWriter->writeElement('date', $row[2]); $xmlWriter->endElement(); } }}$xmlWriter->endElement();$xmlWriter->endDocument();?>\[/code\]This script creates the xml file but unfortunately produces no output inside of it.Would someone be able to help me by pointing out where I am going wrong? I am no expert with this but trying my hardest to learn.Your help is very much appreciated!
 
Back
Top