Madamadam
Madamadam

Reputation: 938

SimpleXML: Selecting parent node based on content of child element

This should be am easy task, but I just didn't get it working: In the below code snippet, I would like to select the <WebFilterCategory> node which has a <Name> child that has a value of "Categoryname2":

<?php
$xmlstring = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Request>
  <Login>
    <UserName>admin</UserName>
    <Password>admin</Password>
  </Login>
  <Set Operation="get">
    <WebFilterCategory transactionid="">
      <Name>Categoryname1</Name>
      <Classification>Objectionable</Classification>
      <DomainList>
        <Domain>example1.com</Domain>
        <Domain>example2.com</Domain>
      </DomainList>
    </WebFilterCategory>
    <WebFilterCategory transactionid="">
        <Name>Categoryname2</Name>
        <Classification>Objectionable</Classification>
        <DomainList>
            <Domain>example1.org</Domain>
            <Domain>example2.org</Domain>
        </DomainList>
    </WebFilterCategory>
  </Set>
</Request>
XML;

$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");
foreach ($xml->query('//WebFilterCategory/Name[contains(., "Categoryname2")]') as $category) {
    print_r($xmlstring);
}
?>

Probably, there's a much leaner query to get the desired result, too.

Upvotes: 0

Views: 273

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

The method you are looking for is not query but xpath

Then you could update the path to match the WebFilterCategory where the Name contains Categoryname2

//WebFilterCategory[Name[contains(., "Categoryname2")]]' 

Updated code

$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");
foreach ($xml->xpath('//WebFilterCategory[Name[contains(., "Categoryname2")]]') as $category) {
    print_r($category);
}

Output

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [transactionid] => 
        )

    [Name] => Categoryname2
    [Classification] => Objectionable
    [DomainList] => SimpleXMLElement Object
        (
            [Domain] => Array
                (
                    [0] => example3.org
                    [1] => example2.org
                )

        )

)

See a Php demo

Upvotes: 1

Related Questions