tags:

views:

31

answers:

3

I'm reading from an API that returns paginated XML. The basic format of the API's output is:

<candidates.list page="1" next_page="yes">
  <candidate />
  <candidate />
  <candidate />
</candidates.list>

My code is like this:

while (TRUE) {
  $xml_str = file_get_contents($dest)
  $xml = new SimpleXMLElement($xml_str);

  // What should I do to append subsequent pages to my first page's XML?

  if ( $xml['next_page'] == 'yes' ) {
    $dest = $new_destination;  // I figure out the next page's API query here
  }
  else {
    break;
  }
}

return $xml;

Happy 4th of July, and thank you!!

A: 

I would append the next page's candidates into your $xml. You have already parsed the XML into a SimpleXMLElement. Or build your own array of SimpleXMLElement candidate objects if that's all you care about.

As a side note, while(1) is bad form. You could change your logic or use a do/while() loop.

Happy 4th back!

Jason McCreary
I guess the question is, HOW should I append the next page's candidates into $xml? Unless I'm missing something, SimpleXML doesn't seem to have an easy way to append new nodes.
Summer
A: 

SimpleXML was the wrong tool for the job. SimpleXML is not designed for adding new nodes, or doing any kind of manipulation really. I switched to using DOMDocument, and was quickly able to create a solution using the appendChild function.

Summer
A: 

Yes, you have to use DOM-based solutions or build a different data structure on the fly with (for example) a SAX approach. DOM doesn't scale well for high throughput (the object memory footprint is very heavy), so if this is the only manipulation you are doing, you might want to consider SAX if you need to scale up.

Dak