How to Find an XML Node by Value in PHP?

You can find an XML node by value in PHP, in the following ways:

Loop Over Nodes and Find a Match

You can simply loop over the XML nodes till you find a match. For example, let's suppose you have the following XML of customers:

$xmlStr =<<<XML
<?xml version="1.0"?>
    <customers>
        <customer>
            <name>John Doe</name>
            <age>24</age>
        </customer>
        <customer>
            <name>Jane Doe</name>
            <age>29</age>
        </customer>
        <customer>
            <name>Bruce Wayne</name>
            <age>39</age>
        </customer>
    </customers>
XML;

To find a customer by the name "Jane Doe", you would do the following:

$xml = new SimpleXMLElement($xmlStr);

foreach ($xml->customer as $customer) {
    if ((string) $customer->name === 'Jane Doe') {
        // do something...
    }
}

Similarly, you can also do look-up for partially matching values, for example, by using str_contains():

$xml = new SimpleXMLElement($xmlStr);

foreach ($xml->customer as $customer) {
    if (str_contains((string) $customer->name, 'Doe')) {
        // do something...
    }
}

Use XPath

You can also make use of xpath to directly select a specific node by value. For example, let's suppose you have the following XML of customers:

$xmlStr =<<<XML
<?xml version="1.0"?>
    <customers>
        <customer>
            <name>John Doe</name>
            <age>24</age>
        </customer>
        <customer>
            <name>Jane Doe</name>
            <age>29</age>
        </customer>
        <customer>
            <name>Bruce Wayne</name>
            <age>39</age>
        </customer>
    </customers>
XML;

To find a customer by the name "Jane Doe", you would do the following:

$xml = new SimpleXMLElement($xmlStr);

// select node by value and return its parent node
$node = $xml->xpath('//customers/customer/name[text()="Jane Doe"]/parent::*');

var_dump($node);

/* output: array(1) {
  [0]=>
  object(SimpleXMLElement)#2 (2) {
    ["name"]=>
    string(8) "Jane Doe"
    ["age"]=>
    string(2) "29"
  }
} */

Similarly, you can also do look-up for partially matching values using the xpath contains() function, for example, like so:

$xml = new SimpleXMLElement($xmlStr);

// select node by value and return its parent node
$node = $xml->xpath('//customers/customer/name[contains(text(), "Doe")]/parent::*');

var_dump($node);

/* output: array(2) {
  [0]=>
  object(SimpleXMLElement)#2 (2) {
    ["name"]=>
    string(8) "John Doe"
    ["age"]=>
    string(2) "24"
  }
  [1]=>
  object(SimpleXMLElement)#3 (2) {
    ["name"]=>
    string(8) "Jane Doe"
    ["age"]=>
    string(2) "29"
  }
} */

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.