SimpleXMLElement Get Value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
J0kerz
Forum Commoner
Posts: 37
Joined: Fri May 29, 2009 2:51 pm

SimpleXMLElement Get Value

Post by J0kerz »

Hi guys,

I am trying to get a value from a node within an XML response.

Here is the code:

Code: Select all

$xml = '

<NotificationService Version="2.3">
	<NotificationList>
		<Tags>
			<Tag Name="Apple">gdfgfdsgdsg</Tag>
			<Tag Name="Banana">hgfhfghfgh</Tag>
			<Tag Name="Orange">fghfghfghgf</Tag>
		</Tags>
	</NotificationList>
</NotificationService>

';

$xml_element = new SimpleXMLElement($xml);

//How to get the value from the node with the attribute Name="Banana" ? 

I am trying to get the value of a node based on its attribute. For example, in the example above, if I would like to get the value of the tag Name Banana, I would do:

Code: Select all

$xml_element->NotificationList->Tags->Tag[1] 

The thing is that the XML response I receive does not always have the node in the same order, so for example, in the example, the banana tag could sometime be the first node instead of the second etc..

I am trying to get the value of a node based on its attribute so that way, it doesnt matter in wich order the node are, I will always get the right value.

I tried something like this, but it is not working:

Code: Select all

$xml_element->NotificationList->Tags->Tag['banana'] 
How can I do that?
Thanks alot!
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: SimpleXMLElement Get Value

Post by McInfo »

Code: Select all

// XPath path to Tag nodes with Name attribute equal to "Banana"
$path = '/NotificationService/NotificationList/Tags/Tag[@Name="Banana"]';
// An array of SimpleXMLElement objects matching the path
$banana_tags = $xml_element->xpath($path);
// Defensive programming, just in case no nodes were found
if (isset($banana_tags[0])) {
    // The first node, cast as a string to get the value
    $node_value = (string)$banana_tags[0];
}
Post Reply