开发者

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</manufact开发者_开发知识库urer>
<manufacturer>Boss</manufacturer>
</data>


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.


$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜