getaway
getaway

Reputation: 8990

output or write to a xml file?

$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

Upvotes: 2

Views: 6694

Answers (2)

Josh Davis
Josh Davis

Reputation: 28730

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

Upvotes: 1

RageZ
RageZ

Reputation: 27313

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

Upvotes: 6

Related Questions