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.

1
  • Without libraries? Or just third-party libraries? Commented Jan 9, 2012 at 5:29

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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.
is there a way to reverse this for generating the xml?
$xml->asXML(); will return the xml string; so you can modify the XML using any of these methods, then when you need to store or display the xml: echo $xml->asXML(); will echo the xml.
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 and other questions on Stack Overflow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.