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

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

getaway
  • 8,792
  • 22
  • 64
  • 94

2 Answers2

6

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());
RageZ
  • 26,800
  • 12
  • 67
  • 76
1

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');
Josh Davis
  • 28,400
  • 5
  • 52
  • 67
  • The problem with using $xml->asXML('data.xml'); is when your xml is malformed for example if you are receiving xml from a remote Api via curl and you try and save it. It won't save and give you error cannot use asXML on Boolean – user3548161 May 08 '18 at 11:46