-1

I have 4 SimpleXMLElement objects that get output from within a foreach loop?

I need to combine the 4 objects into 1 object before outputting to xml. This is what I'm stuck on.

$auth_tokens = array('tok1', 'tok2', 'tok3', 'tok4');

foreach($auth_tokens as $auth_token) { // 4 iterations in loop
    $response = curl_exec($connection); // API xml response
    $xml = simplexml_load_string($response); // loaded xml into object


$entries = $xml->PaginationResult->TotalNumberOfEntries;
$xml = $xml->OrderArray->Order; // Only want this section of each object

if($entries == 0) {
    continue;
}

echo '<pre>' . var_export($xml, true) . '</pre><br>';

}

Output: condensed version of objects

SimpleXMLElement::__set_state(array(
   'OrderID' => '1118',
));


SimpleXMLElement::__set_state(array(
   'OrderID' => '3916',
));


SimpleXMLElement::__set_state(array(
   'OrderID' => '1628',
));


SimpleXMLElement::__set_state(array(
   'OrderID' => '3724',
));

After the 4 objects are combined, I will echo $xml->asXml() outside the loop and be able to add my parent node.

foreach($auth_tokens as $auth_token) {
    // ....
}

$xml = simplexml_load_string("<Orders>$xml</Orders>");
header('content-type: text/xml');
echo $xml->asXML();

How can I get those 4 objects merged into 1 and not have to do anymore loops to make it happen?

1 Answer 1

0

A very simple way of doing this would be to export each piece of XML and add it to a string ($orders) inside the loop, then add this to your final call to simplexml_load_string()...

$orders = "";
foreach($auth_tokens as $auth_token) {
    // ....

    //echo '<pre>' . var_export($xml, true) . '</pre><br>';
    $orders .= $xml->asXML();
}

$xml = simplexml_load_string("<Orders>$orders</Orders>");
header('content-type: text/xml');
echo $xml->asXML();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. I had already figured it out that I need to use $xml->asXML(); inside the loop and concatenate to a variable.

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.