Kavvson Empcraft
Kavvson Empcraft

Reputation: 443

Parsing XML - get node based on children

I am struggeling to get the node based on the children. So I wan't to get the full person by id 4061106. I am using SimpleXMLElement, for now I did a foreach loop to display all persons but I cannot figure out how to get by a specific id. I do not even know where to start from.

<list>
        <person>
            <id>4061106</id>
            <name>Stefan</name>
            <country></country>
            <is_admin>0</is_admin>
            <lastCallbackTime></lastCallbackTime>

        </person>
        <person>
            <id>4082930</id>
            <name>Mike</name>
            <is_admin>0</is_admin>
            <lastCallbackTime></lastCallbackTime>

        </person>
</list>

Upvotes: 0

Views: 27

Answers (1)

iainn
iainn

Reputation: 17417

You need to use Xpath to find the node with the correct value, and then jump back up to the parent node.

$xml = '
  <list>
    <person>
      <id>4061106</id>
      <name>Stefan</name>
      <country></country>
      <is_admin>0</is_admin>
      <lastCallbackTime></lastCallbackTime>
    </person>
  </list>
';

$sxml = simplexml_load_string($xml);
$person = $sxml->xpath('/list/person/id[.="4061106"]/parent::person')[0];

echo (string) $person->name; // Stefan

Upvotes: 2

Related Questions