Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...