How to parse data back to an XML file using SimpleXML?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Still Learning
Forum Commoner
Posts: 25
Joined: Tue Jan 27, 2009 3:57 pm
Location: Philadelphia

How to parse data back to an XML file using SimpleXML?

Post by Still Learning »

I just learned how to extract data from my xspf files(which work the same as XML) using Simple XML, and was able to store each attribute I needed to different variables. Is there an efficient way to parse them back say, in a different order?

Can Simple XML be used, or do I have to use a different XML Parser?

This is the code I used to extract the data, and it works well. All the outputs are exactly as I wanted, so the variables are holding the correct data. Just need to know how to write back to the file using XML parsing.

Code: Select all

<?php
 
$xml = simplexml_load_file("Artist.xspf");
$i=0;
 
 
foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
 
foreach($xml->tracklist->children() as $child)
  {
  echo $child->getName() . ": " . $child . " : ";
  $songname[$i]= $xml->tracklist->track[$i]->annotation;
  echo $songname[$i] . "<br />";
  $tracklocation[$i]= $xml->tracklist->track[$i]->children();
  echo "Song Location: " . $tracklocation[$i];
 
 
  $songimage[$i]= $xml->tracklist->track[$i]->image;
  echo "<br />Image URL = " . $songimage[$i] . "<br /><br />";
   $i++;
  }
 
echo "<br />Artist has " . $i . " tracks";
echo "<br />The 4th track's location is: " . $tracklocation[3];
echo "<br />It's name is " . $songname[3];
?>
 
User avatar
nor0101
Forum Commoner
Posts: 53
Joined: Thu Jan 15, 2009 12:06 pm
Location: Wisconsin

Re: How to parse data back to an XML file using SimpleXML?

Post by nor0101 »

The SimpleXMLElement class provides an asXML() method. You can optionally pass in a string $filename to write the XML 1.0 data to that file instead of returning it as a string.

See the docs: http://us.php.net/manual/en/function.si ... -asXML.php
Still Learning
Forum Commoner
Posts: 25
Joined: Tue Jan 27, 2009 3:57 pm
Location: Philadelphia

Re: How to parse data back to an XML file using SimpleXML?

Post by Still Learning »

Cool. That seems simple enough. So once I change the values of all the children to what they need to be, I just send it back asXML(string $filename).

Thanks so much for the tip!

I was originally treating the entire file as just a data string, and trying to extract elements using string functions, which was entirely too much work. This board rocks. I'm very thankful for the help I've been given. :D
Post Reply