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

我使用此脚本将文本文件转换为 xml 文件,但我想将其输出到文件,我该怎么做这个 simpleXML,干杯

4

2 回答 2

6

file_put_contents功能会做到这一点。该函数获取文件名和一些内容并将其保存到文件中。

因此,重新使用您的示例,您只需将 echo 语句替换为file_put_contents.

$xml = new SimpleXMLElement('<allproperty></allproperty>');
$fp = fopen('data.txt', 'r');

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]);
}

file_put_contents('data_out.xml',$xml->saveXML());
于 2010-12-15T02:40:25.097 回答
1

作为记录,您可以使用 asXML() 。我的意思是,它就在手册中,只要阅读它,你的生活就会变得更轻松。(我认为,也许向 StackOverflow 询问基本的东西对某些人来说更容易)

此外,这个更间接,您不一定需要addChild()为每个孩子使用。如果没有该名称的子项,则可以使用对象属性表示法直接分配它:

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

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

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

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

$xml->asXML('data.xml');
于 2010-12-15T09:50:38.703 回答