data.txt

ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5

i want convert this textfile into xml using simplexml module using php? thanks :))

p.s. im new to this

EDIT:

<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>

Comments

Start: file() to parse the file into lines; explode() to split up the columns

Written by Pekka

Then put together a DOMDocument: stackoverflow.com/questions/1933563/… and write it out into a file

Written by Pekka

My mind-reading is a little slow today. Could you just tell us what format you want it in? Thx.

Written by Jonah

@Pekka: The OP specifically asked for SimpleXML.

Written by Jonah

xml file :)) @jonah bron

Written by getaway

@getaway: No, how do you want it? What tag names?

Written by Jonah

let me update my answer sorry!

Written by getaway

Accepted Answer

Although I think XMLWriter is best suited for that task (like in my other answer), if you really want to do it with SimpleXML, here's how:

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

You will notice that the output is not as clean: it's because SimpleXML doesn't allow you to automatically indent tags.

Written by netcoder
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki