9

I am trying to import each story into an object. Each object will have multiple strings (start and end) along with arrays generated from content in the additional-content. An small example would be:

<feed>
  <story>
    <run>
      <start>1/1/2012</start>
      <end>3/1/2012</end>
    </run>
    <additional-content>
      <content>
         <sample>Sample story example</sample>
      </content>
      <content>
         <sample>Sample story example</sample>
      </content>
    </additional-content>
</story>
...
</feed>

I all the xml being imported to a string. Also, I am trying to do this without libraries. I understand looping through each story but am unsure how to load the content into the object while also generating the array correctly. Any help would be appreciated.

Matthew Sprankle
  • 1,626
  • 1
  • 19
  • 26

1 Answers1

14

simplexml loads xml into an object and you'll be able to work with it exactly as you're asking.

$xml = simplexml_load_string($stories);
Francis Lewis
  • 8,872
  • 9
  • 55
  • 65
  • Word-up! Now that's really using XML. IMHO, it's silly to shred XML into native data types, especially if you're just doing string manipulation. Creating objects that operate on XML objects (nodes, documents) is way better and more flexible than shredding XML. – William Walseth Jan 09 '12 at 20:13
  • is there a way to reverse this for generating the xml? – Matthew Sprankle Jan 13 '12 at 00:13
  • `$xml->asXML();` will return the xml string; so you can modify the XML using any of [these methods](http://www.php.net/manual/en/book.simplexml.php), then when you need to store or display the xml: `echo $xml->asXML();` will echo the xml. – Francis Lewis Jan 13 '12 at 00:36
  • 4
    Watch out! A SimpleXMLElement behaves like an object, but it's a RESOURCE for the original data. That's why, for example, comparisons between two SimpleXMLElements that seems to be identical always returns false. Try asXML() after simplexml_load_string and you'll see. Some links [from comments PHP manual](http://www.php.net/manual/pt_BR/class.simplexmlelement.php#100811) and [other questions on Stack Overflow](http://stackoverflow.com/questions/17935118/compare-simplexml-object) – thicolares Aug 30 '13 at 21:29