1

I have following script:

<?php
    $xml = '<?xml version="1.0" encoding="UTF-8"?>
            <root>
                <category id="1" sort="00A125698" name="Kitchen">
                    <good id="122"/>
                    <good id="315"/>
                    <good id="94"/>
                </category>
                <category id="2" sort="00B354565" name="Dining room">
                    <good id="441"/>
                    <good id="122"/>
                    <good id="521"/>
                </category>
                <category id="3" sort="00A259875" name="Chairs">
                    <good id="335"/>
                    <good id="225"/>
                </category>
            </root>';

    $data = simplexml_load_string($xml);
    $cat_name = $data->xpath("/root/category[contains(@sort, '00A')] && /root/category/good[@id='122']");

    $cat_name_cnt = count($cat_name);
    for($i = 0; $i <$cat_name_cnt; $i++){
        echo $cat_name[$i]->attributes()->name;
        echo '<BR />';
    }
?>

I don't know if it is possible, but I try to do something like: Display the name of the category where the attribute sort begins with "00A" and whose child's id is 122. I know that the first part of the XPath is right, but I don't know how to do the part "whose child is".

The output should be Kitchen.

I know that there would possible to display all category names whose sort begins 00A and then test in PHP if an array of goods contains 122. But I think that it's faster to make it immidiately in XPath if it is possible.

Thank you!

Kevin
  • 41,694
  • 12
  • 53
  • 70
Michal Vlasák
  • 247
  • 2
  • 14

1 Answers1

1

Yes it's quite possible, actually you're almost there. Example:

$data = simplexml_load_string($xml);
$cat_name = $data->xpath("/root/category[contains(@sort, '00A')][descendant::good[@id='122']]");
if(count($cat_name) > 0) {
    $element = $cat_name[0];
    $name = (string) $element->attributes()->name;
    echo $name; // kitchen
}
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Kevin
  • 41,694
  • 12
  • 53
  • 70