Lukas Lunow
Lukas Lunow

Reputation: 577

Selecting text node based on value of it's sibling in PHP using SimpleXML

I have XML with format comparable to this below:

<users>
  <user>
    <name>Mac</name>
    <category>4</category>
  </user>
  <user>
   <name>Simon</name>
    <category>3</category>
  </user>
  <user>
    <name>Jim</name>
    <category>4</category>
  </user>
</users>

What I would like to do is interate through users in a specific category and returning their names. I have been doing some work using simplexml, but I have been unable to figure out how to select element node based on text in it's sibling.

foreach ($users->user as $user) {
echo (string)$user->name; 
}

Thank you in advance

Upvotes: 0

Views: 211

Answers (1)

ThW
ThW

Reputation: 19512

Use Xpath:

$users = simplexml_load_string($xml);
foreach($users->xpath('//user[category = 4]') as $user) {
  echo (string) $user->name, "\n";
}

Output:

Mac
Jim

btw This is how it would look with DOM:

$xpath = new DOMXpath(DOMDocument::loadXml($xml));
foreach ($xpath->evaluate('//user[category = 4]') as $user) {
  echo $xpath->evaluate('string(name)', $user), "\n";
}

Upvotes: 1

Related Questions