1

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

2

4 Answers 4

1

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 
Sign up to request clarification or add additional context in comments.

Comments

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

PHP attributes() Function

Comments

0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.