Ryan
Ryan

Reputation: 14649

Convert text file contents to XML

I have a text file that contains a list of manufacturers. How can I read the lines of the file via PHP and write a new XML file that contains all of characters on each line of text file (the manufacturer's name)?

Text file:

Sony
Pioneer
Boss

The XML file to be written would look like this:

<data>
<manufacturer>Sony</manufacturer>
<manufacturer>Pioneer</manufacturer>
<manufacturer>Boss</manufacturer>
</data>

Upvotes: 0

Views: 1999

Answers (2)

alex
alex

Reputation: 490363

I'd use file() for opening the file, DOMDocument (or you could use SimpleXML) for building the XML structure and file_put_contents() for saving the resulting XML to file.

$manufacturers = file('manufactures.txt');

$dom = new DOMDocument;

$data = $dom->createElement('data');

$dom->appendChild($data);

foreach($manufacturers as $manufacturer) {
   $manufacturerElement = $dom->createElement('manufacturer');
   $text = $dom->createTextNode($manufacturer);
   $manufacturerElement->appendChild($text);
   $data->appendChild($manufacturerElement);
}

file_put_contents('manufactures.xml', $dom->saveXML());

CodePad.

Also, Dan Grossman's answer answer has the good idea of using trim() on the text node before inserting it.

Upvotes: 4

Dan Grossman
Dan Grossman

Reputation: 52372

$lines = file('something.txt');

$xml = "<data>\n";
foreach ($lines as $line) {
    $xml .= "<manufacturer>" . trim($line) . "</manufacturer>\n";
}
$xml .= "</data>";

file_put_contents('something.xml', $xml);

Upvotes: 2

Related Questions