Search code examples
phpxmlsimplexmldepagination

How can I reconstruct a paginated XML document?


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


Solution

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