【问题标题】:Wrap array around SimpleXML object围绕 SimpleXML 对象包装数组
【发布时间】:2014-04-28 11:54:57
【问题描述】:

我确实从 Web 服务接收 XML 结果,我将其读取为 SimpleXML 元素。现在存在结果可能因 Web 服务提供的配置而异的情况。

重点是:我想在“情况 2”中围绕 SimpleXML 对象包装一个数组,因此在处理后面的数据。一段时间以来,我一直在寻找和思考解决方案,但到目前为止我还没有弄清楚任何事情。

情况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"
  }
}

【问题讨论】:

  • 检查myConfig是否是一个数组,如果不是就简单地把它变成一个......

标签: php arrays simplexml


【解决方案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']);
    }
}

【讨论】:

    【解决方案2】:

    这听起来很简单:

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

    【讨论】:

    • 那样对我不起作用。在 PHP 5.3 中使用您的代码时出现错误:警告:尚无法在第 70 行的 getConfig.php 中将复杂类型分配给属性
    • 对,在这种情况下,您需要先取消设置$fooConfig['myConfig'],然后才能再次设置它。我的一点疏忽,请参阅编辑。
    • 我认为这仍然行不通,至少对于 SimpleXML 不行。不幸的是,简单地将 XML 对象分配到 XML 结构中是行不通的(同样的错误)。也许有一个循环,我明天试试。但总的来说,您提供了一个很好的解决方案,可以按照我的要求将数组包裹在对象周围。现在更多的是把它放回正确的地方。也许 SimpleXML 不适合在这里使用。
    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2010-09-15
    • 1970-01-01
    相关资源
    最近更新 更多