PHP在foreach循环中将4个SimpleXMLElement对象合并为1个

时间:2018-10-26 04:30:29

标签: php xml simplexml

我有4个SimpleXMLElement对象,它们从foreach循环中获取输出?

在输出到xml之前,我需要将4个对象合并为1个对象。这就是我所坚持的。

$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>';

}

输出:对象的精简版本

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


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


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


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

将4个对象合并后,我将echo $xml->asXml()移出循环并能够添加我的父节点。

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

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

如何将这4个对象合并为1,而不必再执行循环来实现它?

1 个答案:

答案 0 :(得分:0)

一种非常简单的方法是将每段XML导出并添加到循环内的字符串(int height = Screen.PrimaryScreen.Bounds.Height; int width = Screen.PrimaryScreen.Bounds.Width; width = SystemInformation.VirtualScreen.Width; height = SystemInformation.VirtualScreen.Height; )中,然后将其添加到对$orders的最终调用中。

simplexml_load_string()