2010-12-15 44 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 

我想使用SimpleXML模块使用PHP这个文本文件转换成XML?谢谢:))

p.s.即时通讯新本

编辑:

<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()'将文件解析为行; '爆炸()'分裂列 – 2010-12-15 01:07:03

+0

然后放在一起DOMDocument:http://stackoverflow.com/questions/1933563/creating-dynamic-xml-with-php并将其写入文件 – 2010-12-15 01:08:01

+0

我的思维阅读今天有点慢。你能告诉我们你想要什么样的格式吗?谢谢。 – Jonah 2010-12-15 01:08:02

回答

3

虽然我觉得XMLWriter是最适合这个任务(like in my other answer),如果你真的想用SimpleXML做到这一点,方法如下:

$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 2010-12-15 01:30:23

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

即时通讯设法学习与simplexml,我爱你的代码虽然!欢呼声 – getaway 2010-12-15 01:18:53