1
votes

i converted xml string into a simpleXMLElement object using simplexml_load_string whose value on print_r outputs

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 ) ) ))

How can I extract node and attribute values from this object? Using

echo $xml->body 

to get content of the body node is not outputting any value

UPDATE:

XML string

 <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>

Would like to extract both the node values and attributes

4
please edit your question and include the xml string - Alex Andrei

4 Answers

1
votes

Assuming $string holds the xml string in your question

To get the value of an individual xml node

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

Will output

To be or not to be!

To get a specific attribute from a specific node

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

Will output

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

PHP attributes() Function

0
votes

Look up SimpleXMLElement documentation on php.net: http://php.net/manual/en/class.simplexmlelement.php

There is a list of methods for this class and one of them is attributes, which returns all of element attributes: http://php.net/manual/en/simplexmlelement.attributes.php

I believe taking a look at Basic Usage of SimpleXML will also help: http://php.net/manual/en/simplexml.examples-basic.php

0
votes

Simplest solution is:

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

if you want to use advance php functionality then iterator is good option:

$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><br />";
        foreach ($node->attributes() as $attr => $value) {
            echo "   Attribute: <b>" . $attr . "</b> - value: <b>".$value."</b><br />";
        }
    } else{
        echo "Node Name: <b>".$nodeName."</b> - value: <b>".$node->__toString()."</b><br />";
    }
}

In above iterator loop you can play with node and attributes.

You can also get the value of noe and attribute as @AlexAndrei mentioned in his answer.