2011-07-19 8 views
0

メーカーの一覧を含むテキストファイルがあります。どのように私はPHPを介してファイルの行を読むことができ、テキストファイルの各行(メーカーの名前)のすべての文字を含む新しいXMLファイルを書き込むことができますか?テキストファイルの内容をXMLに変換する

テキストファイル:

Sony 
Pioneer 
Boss 

を書き込まれるXMLファイルは次のようになります。

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

答えて

4

私は、ファイルを開くためのfile()を使用したい、DOMDocument (またはSimpleXMLを使用して)XML構造を構築し、file_put_contents()結果のXMLをファイルに保存します。

$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

また、Dan Grossman's answer答えは、それを挿入する前にテキストノードでtrim()を使用することをお勧めします。

2
$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); 
+1

よろしくお願いします。XMLをテキストとして扱わないでください。文字エンコーディングを手動で処理する必要があります –

関連する問題