PHP从SimpleXMLElement数组中获取值

pvabu6sv  于 2023-01-24  发布在  PHP
关注(0)|答案(5)|浏览(109)

我有这个:

[1]=>
object(SimpleXMLElement)#6 (1) {
  ["@attributes"]=>
  array(14) {
    ["name"]=>
    string(5) "MySQL"
    ["acknowledged"]=>
    string(1) "1"
    ["comments"]=>
    string(1) "1"
    ["current_check_attempt"]=>
    string(1) "1"
    ["downtime"]=>
    string(1) "0"
    ["last_check"]=>
    string(19) "2010-05-01 17:57:00"
    ["markdown_filter"]=>
    string(1) "0"
    ["max_check_attempts"]=>
    string(1) "3"
    ["output"]=>
    string(42) "CRITICAL - Socket timeout after 10 seconds"
    ["perfdata_available"]=>
    string(1) "1"
    ["service_object_id"]=>
    string(3) "580"
    ["state"]=>
    string(8) "critical"
    ["state_duration"]=>
    string(6) "759439"
    ["unhandled"]=>
    string(1) "0"
  }
}

(我使用了var_dump($child)来生成它)
如何将"name"属性作为字符串从其中取出?
下面是我的代码:

$xml = simplexml_load_string($results);

foreach($xml->data->list as $child) {
var_dump($child);
  echo $child->getName() . ": " . $child->name . "<br />";
  }
cbjzeqam

cbjzeqam1#

使用SimpleXML,您可以获得:

  • 子元素,使用对象表示法:$element->subElement
  • 和属性,使用数组表示法:$element['attribute']

所以,在这里,我会说你必须用途:

echo $child['name'];

作为一个参考,也有一些例子,请参见simplexml手册的Basic usage部分。

Example #6应该是一个有趣的例子,关于属性。

f0ofjuux

f0ofjuux2#

您可以执行以下操作:

echo $child['name'];

要查看其值,应该注意$child['name']是一个对象,而不是字符串。回显它会将其转换为字符串,因此它在那种情况下有效。但如果要将其存储在某个地方,最好自己将其转换为字符串:

$name = (string) $child['name'];
dced5bon

dced5bon3#

有点乱不过我成功地用了这个

foreach($xml->data->children() as $child) {
//var_dump($child);
    foreach ($child->attributes() as $a => $b) {
     echo $a . '=' . $b . '<br />';
    }
}

不知道为什么,OpsView API返回一个二维数组,而不是每个XML节点只有一个值:(

echo $child['name'];

很好用,而且更优雅,谢谢。

xpcnnkqh

xpcnnkqh4#

我也遇到过类似的问题,我需要从SimpleXMLElement中取出字符串,但找不到调用它的名称。找到了解决方案,使用(string)获取字符串文本:

foreach ($lines as $line) {
    array_push($result, new line(**(string)**$line));
}

array
  0 => 
    object(line)[190]
      private '_line' => 
        object(SimpleXMLElement)[128]
          public '@attributes' => 
            array
              ...
          string ' ' (length=1)
  1 => 
    object(line)[191]
      private '_line' => 
        object(SimpleXMLElement)[131]
          public '@attributes' => 
            array
              ...
          string ' ' (length=1)
  2 => 
    object(line)[192]
      private '_line' => 
        object(SimpleXMLElement)[132]
          public '@attributes' => 
            array
              ...
          string ' ~54**** I N V O I C E ****' (length=27)
ckocjqey

ckocjqey5#

当我第一次遇到这个的时候,我真的很困惑。当我试图得到整个数组的时候,我似乎被返回了数组中的第一个对象!在我的示例中,“item”是一个对象数组,而下面的代码只返回了数组中的第一个对象!

$response->channel->item

然而,如果像我一样,你想访问所有的对象,你可以只循环项目,所以不是一个真正的问题。只是真的很奇怪!

foreach($response->channel->item as $item) {
    ray($item);
}

相关问题