output or write to a xml file?

淺唱寂寞╮ 提交于 2019-12-10 11:44:22

问题


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

im using this script to convert text file into a xml file, but i want to output it to a file, how can i do this simpleXML, cheers


回答1:


file_put_contents function would do it. The function take a filename and some content and save it to the file.

So retaking your example you would just to replace the echo statement by 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());



回答2:


For the record, you can use asXML() for that. I mean, it's right there in the manual, just read it and your life will get easier. (I assume, perhaps asking StackOverflow for basic stuff is easier for some)

Also, and this one is more circumstantial, you don't necessarily need to use addChild() for every child. If there is no child of that name, it can be assigned directly using the object property notation:

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


来源:https://stackoverflow.com/questions/4446192/output-or-write-to-a-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!