/    Sign up×
Community /Pin to ProfileBookmark

SimpleXMLElement Get Value

Hi guys,

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

Here is the code:

[code=php]$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” ?[/code]

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=php]$xml_element->NotificationList->Tags->Tag[1][/code]

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=php]$xml_element->NotificationList->Tags->Tag[‘banana’][/code]

How can I do that?

Thanks alot!

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@tracknutJul 01.2011 — You could use xpath, like this:
<i>
</i>$str = "/NotificationService/NotificationList/Tags/Tag[@Name='Banana']";
$result = $xml_element-&gt;xpath($str);
if ($result)
echo $result[0];
else
echo "Yes, we have no bananas";
Copy linkTweet thisAlerts:
@J0kerzauthorJul 01.2011 — Thanks ! ?

I still got one last small question: How can I check if the Tag with the attribute "Name=Banana" exist?

I tried the following but no chance yet:

[code=php]if(!empty($xml_element->NotificationList->Tags->xpath("Tag[@Name='Banana']"))){

//Banana Exist!!

}[/code]
Copy linkTweet thisAlerts:
@tracknutJul 01.2011 — The code I provided tells you (in the "else" branch) if you have no "banana" tag. As to your code, give it a shot, I have no idea if that'll work!

Dave
×

Success!

Help @J0kerz spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...