2010-12-15 22 views
2

data.txtをphpを使用してテキストファイルをxmlに変換しますか?

ha15rs,250,home2.gif,2 
ha36gs,150,home3.gif,1 
ha27se,300,home4.gif,4 
ha4678,200,home5.gif,5 

は、PHPを使用してのSimpleXMLモジュールを使用してXMLには、このテキストファイルを変換したいですか?ありがとう:)

p.s.この

EDITに新しいイム:

<allproperty> 
      <aproperty> 
        <postcode></postcode> 
        <price></price> 
        <imagefilename></imagefilename> 
        <visits></visits> 
       </aproperty> 
       <aproperty> 
        <postcode></postcode> 
        <price></price> 
        <imagefilename></imagefilename> 
        <visits></visits> 
       </aproperty> 
       <aproperty> 
        <postcode></postcode> 
        <price></price> 
        <imagefilename></imagefilename> 
        <visits></visits> 
       </aproperty> 
      </allproperty> 
+0

開始:ファイルを行に解析する 'file()'; 'explode()'を使って列を分割する –

+0

DOMDocumentをまとめて:http://stackoverflow.com/questions/1933563/creating-dynamic-xml-with-phpそしてファイルに書き出してください –

+0

私の読書今日は少し遅いです。あなたはそれを望む形式を教えてください。どうも。 – Jonah

答えて

3

私はあなたが本当にのSimpleXMLでそれをしたい場合はXMLWriterは、そのタスク(like in my other answer)に最も適していると思いますが、ここで方法は次のとおりです。あなたが出力としてきれいではないことがわかります

$fp = fopen('data.txt', 'r'); 

$xml = new SimpleXMLElement('<allproperty></allproperty>'); 

while ($line = fgetcsv($fp)) { 
    if (count($line) < 4) continue; // skip lines that aren't full 

    $node = $xml->addChild('aproperty'); 
    $node->addChild('postcode', $line[0]); 
    $node->addChild('price', $line[1]); 
    $node->addChild('imagefilename', $line[2]); 
    $node->addChild('visits', $line[3]); 
} 

echo $xml->saveXML(); 

:それはですSimpleXMLでは自動的にタグをインデントできないためです。

+0

おかげでスター!それについて申し訳ありません、私のおかげでピアノ、何とか私からもう一度+1正しい答え:)) – getaway

4

私はそれが最も適しているので、あなたが、代わりにXMLWriterを使用することをお勧めします(と、それはまた、内蔵のだSimpleXMLのように):

$fp = fopen('data.txt', 'r'); 

$xml = new XMLWriter; 
$xml->openURI('php://output'); 
$xml->setIndent(true); // makes output cleaner 

$xml->startElement('allproperty'); 
while ($line = fgetcsv($fp)) { 
    if (count($line) < 4) continue; // skip lines that aren't full 

    $xml->startElement('aproperty'); 
    $xml->writeElement('postcode', $line[0]); 
    $xml->writeElement('price', $line[1]); 
    $xml->writeElement('imagefilename', $line[2]); 
    $xml->writeElement('visits', $line[3]); 
    $xml->endElement(); 
} 
$xml->endElement(); 

もちろん、php://output引数をファイルに出力したい場合は、ファイル名に変更することができます。

+0

imはsimplexmlで学習しようとしていますが、あなたのコードは大好きです!歓声 – getaway

関連する問題