Take the 2-minute tour ×

I'm wondering if there is an accepted method to convert a tab delimited text file to XML, so that it can be imported in Adobe Flex. I would prefer to use PHP to achieve this.



The tab delimited text file I am looking to convert is in the format

Refnumber  Location    Name     Age    
123        North America    Steve    32   

And I am looking to convert to

<refnumber> 123 </refnumber> 
<location> North America </location>
<name> Steve </name>
<age> 32 </age>
share|improve this question
Can you post the contents of the TAB-DELIMITED-TEXT-FILE for reference. –  Sujit Agarwal May 26 '11 at 16:08

3 Answers 3

up vote 4 down vote accepted

You can iterate the file line by line and write the contents with XMLWriter

XmlWriter Example (demo)

$xmlWriter = new XMLWriter();
$xmlWriter->startDocument('1.0', 'UTF-8');

$tsvFile = new SplFileObject('filename.tsv');
foreach ($tsvFile as $line => $row) {
    if($line > 0) {
        $xmlWriter->writeElement('refnumber', $row[0]);
        $xmlWriter->writeElement('location', $row[1]);
        $xmlWriter->writeElement('name', $row[2]);
        $xmlWriter->writeElement('age', $row[3]);

Using the XmlWriter has the added benefit that it will tell you when you are trying to write illegal content for the XML elements. If you know there is only valid data in your tsv file, you can also just use a template and write that to another file.

Template Example (demo)

$tsvFile = new SplFileObject('filename.tsv');

$template = <<< TPL

$destFile = new SplFileObject('destination.xml', 'w+');
$destFile->fwrite('<?xml version="1.0" encoding="UTF-8"?>');
    if($line > 0) {
        $destFile->fwrite(vsprintf($template, $row));


share|improve this answer

I'm assuming you already read the Tab-delimited file. You can generate a XML output with something like this:

// get lines here

$xml = '<xml>';

foreach ($lines as $line) {

  // get values from line here
  $xml .= '<data>';

  $xml .= sprintf('<%s>%s</%s>', 'refnumber', $values[0], 'refnumber');
  $xml .= sprintf('<%s>%s</%s>', 'location', $values[1], 'location');
  $xml .= sprintf('<%s>%s</%s>', 'name', $values[2], 'name');
  $xml .= sprintf('<%s>%s</%s>', 'age', $values[3], 'age');

  $xml .= '</data>';

$xml .= '</xml>';
share|improve this answer

If you want to use PHP to do this, you'll need to read your file line by line (i guess a set of data ends with a line-break) and then split the lines using the Tab as delimiter (regular extension is \r).

After that, to create your XML-Output, you'll want to use the XMLWriter-class, which can print the result to the screen (like you opened a normal XML-file), save it on the File-System or write it to a Database (using something like MySQLi).

share|improve this answer

Your Answer


