سؤال

I do receive XML results from a web service which I read as SimpleXML elements. Now there's the situation that results can differ depending on the configuration delivered by the web service.

The point is: I'd like to wrap an array around the SimpleXML object in "Situation 2" so I do not have to differentiate between "config as SimpleXML object inside array" and "config as SimpleXML object" when processing the data later on. I've been looking&thinking for a solution for some time, but as of now I couldn't figure anything out.

Situation 1: Multiple SimpleXML Elements inside an array are returned

["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"
  }
}

Situation 2: Config only contains one SimpleXML element, no array returned by web service

 ["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"
}

Target for situation 2: I would like to create the following out of "Situation 2" on server-side, before continuing to work with the configuration data:

["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"
  }
}
هل كانت مفيدة؟

المحلول

I managed to create and array out of the SimpleXML object this way. It's working fine for the moment, but this way I have to convert my SimpleXML object and continue with a PHP array:

// 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']);
    }
}

نصائح أخرى

This sounds rather trivial:

$test = $fooConfig['myConfig'];

if (is_object($test) && $test instanceof SimpleXMLElement) {
    unset($fooConfig['myConfig']);
    $fooConfig['myConfig'] = array($test);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top