从SimpleXMLElement数组中获取PHP值

3

我有这个:

  [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 />";
  }
5个回答

13

使用SimpleXML,您可以获取:

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


因此,这里我会建议您使用:

echo $child['name'];


作为参考并提供一些例子,可以查看simplexml手册的基本用法部分。

示例#6应该是最有趣的,涉及属性。


我曾经遇到过这个问题,为了将属性作为字符串获取,我不得不在所有属性前面添加(string)。非常令人困惑。(感谢PHP!)编辑:我刚意识到JW.在下面说了同样的话。无论如何,希望这对那些匆忙查看标记为正确答案并且不查看其他答案的人有所帮助。 - HartleySan

13
可以这样做:

虽然你可以这样做:

echo $child['name'];

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

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

2
有点混乱,但我已经成功地使用了这个。
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'];

工作得很好,而且更加优雅,谢谢。

1

当我第一次遇到这个问题时,我感到非常困惑。我试图获取整个数组,但似乎只返回了数组中的第一个对象! 在我的情况下,“item”是一个对象数组,而以下代码只返回了数组中的第一个对象!

$response->channel->item

然而,如果像我一样,您想访问所有对象,只需循环遍历项目即可,因此并不是真正的问题。只是非常奇怪!
foreach($response->channel->item as $item) {
    ray($item);
}

0

我遇到了类似的问题,我需要从我的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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接