首页 文章

从SimpleXMLElement对象中提取节点和属性

提问于
浏览
1

我使用simplexml_load_string将xml字符串转换为simpleXMLElement对象,其print_r输出值

SimpleXMLElement Object ( [message] => SimpleXMLElement Object ( [@attributes] => Array 
                  ( [to] => Danny [type] => greeting [id] => msg1 ) 
                  [body] => To be or not to be! ) [status] => SimpleXMLElement Object ( [@attributes] => Array ( [time] => 2015-01-12 ) [0] => SimpleXMLElement Object ( [@attributes] => Array ( [count] => 0 ) ) ))

如何从此对象中提取节点和属性值?运用

echo $xml->body

获取正文节点的内容不输出任何值

更新:

XML字符串

<start>
  <message to="Danny" type="greeting" id="msg1 ">
    <body>
     To be or not to be!
    </body>
  </message>
  <status time="2015-01-12">
   <offline count="0"></offline>
  </status>
 </start>

想要提取节点值和属性

4 回答

  • 0

    假设 $string 在您的问题中保存xml字符串

    获取单个xml节点的值

    $xml = simplexml_load_string($string);
    print $xml->message->body;
    

    会输出

    To be or not to be!
    

    从特定节点获取特定属性

    print $xml->message->attributes()->{'type'};
    

    会输出

    greeting
    
  • 0
    foreach($xml->body[0]->attributes() as $a => $b)
      {
      echo $a,'="',$b,"<br>";
      }
    

    PHP attributes() Function

  • 0

    在php.net上查找SimpleXMLElement文档:http://php.net/manual/en/class.simplexmlelement.php

    这个类有一个方法列表,其中一个是属性,它返回所有元素属性:http://php.net/manual/en/simplexmlelement.attributes.php

    我相信看看SimpleXML的基本用法也会有所帮助:http://php.net/manual/en/simplexml.examples-basic.php

  • 1

    最简单的解决方案是:

    $xml = simplexml_load_string($str);
    $json = json_encode($xml);
    $array = json_decode($json,TRUE);
    print_r($array);
    

    如果你想使用高级PHP功能,那么迭代器是不错的选择:

    $xml = simplexml_load_string($str);
    $xmlIterator = new RecursiveIteratorIterator(new SimpleXMLIterator($str), RecursiveIteratorIterator::SELF_FIRST);
    foreach ($xmlIterator as $nodeName => $node) {
        if($node->attributes()) {
            echo "Node Name: <b>".$nodeName."</b>
    "; foreach ($node->attributes() as $attr => $value) { echo " Attribute: <b>" . $attr . "</b> - value: <b>".$value."</b>
    "; } } else{ echo "Node Name: <b>".$nodeName."</b> - value: <b>".$node->__toString()."</b>
    "; } }

    在上面的迭代器循环中,您可以使用节点和属性 .

    你也可以在答案中提到@AlexAndrei的noe和属性值 .

相关问题