围绕SimpleXML对象包装数组

时间:2014-04-28 11:54:58

标签: php arrays simplexml

我确实从Web服务接收XML结果,我将其视为SimpleXML元素。现在的情况是,结果会因Web服务提供的配置而有所不同。

关键是:我想在“情境2”中围绕SimpleXML对象包装一个数组,所以我不必在处理时将“config as SimpleXML object into array”和“config as SimpleXML object”区分开来。以后的数据。一段时间以来,我一直在寻找和思考解决方案,但截至目前我无法解决任何问题。

情况1:返回数组中的多个SimpleXML元素

["myConfig"]=>
array(2) {
  [0]=>
  object(SimpleXMLElement)#41 (5) {
    ["id"]=>
    string(1) "1"
    ["type"]=>
    string(1) "4"
    ["comment"]=>
    string(2) "foobar"
    ["name"]=>
    string(1) "test"
    ["attribute"]=>
    string(5) "value"
  }
  [1]=>
  object(SimpleXMLElement)#42 (5) {
    ["id"]=>
    string(1) "4"
    ["type"]=>
    string(1) "2"
    ["comment"]=>
    string(8) "twobar"
    ["name"]=>
    string(10) "test2"
    ["attribute"]=>
    string(5) "value"
  }
}

情况2:Config只包含一个SimpleXML元素,没有Web服务返回的数组

 ["myConfig"]=>
object(SimpleXMLElement)#41 (5) {
  ["id"]=>
  string(1) "1"
  ["type"]=>
  string(1) "4"
  ["comment"]=>
  string(2) "foobar"
  ["name"]=>
  string(1) "test"
  ["attribute"]=>
  string(5) "value"
}

情况2的目标:在继续使用配置数据之前,我想在服务器端创建以下“情境2”:

["myConfig"]=>
array(1) {
  [0]=>
  object(SimpleXMLElement)#41 (5) {
    ["id"]=>
    string(1) "1"
    ["type"]=>
    string(1) "4"
    ["comment"]=>
    string(2) "foobar"
    ["name"]=>
    string(1) "test"
    ["attribute"]=>
    string(5) "value"
  }
}

2 个答案:

答案 0 :(得分:1)

我设法以这种方式创建和排出SimpleXML对象。它目前工作正常,但这样我必须转换我的SimpleXML对象并继续使用PHP数组:

// The SimpleXML Object $myConfig is converted to a PHP array
$fooConfig = json_decode(json_encode((array)$myConfig), TRUE);

// Check if ['id'] is a key in ['myConfig'], go through array if true
// and shift key => value pairs as array inside array
if(array_key_exists('id', $fooConfig['myConfig'])) {
    foreach($fooConfig['myConfig'] as $conKey => $conVal) {
        $fooConfig['myConfig'][0][$conKey] = array_shift($fooConfig['myConfig']);
    }
}

答案 1 :(得分:0)

这听起来相当简单:

$test = $fooConfig['myConfig'];

if (is_object($test) && $test instanceof SimpleXMLElement) {
    unset($fooConfig['myConfig']);
    $fooConfig['myConfig'] = array($test);
}
相关问题