Lee
Lee

Reputation: 4323

How can I use XPath with several attribute values?

I'm fine when I try to filter an XML result by attribute value, when it's in single form, but I want to pass an array of values, and for it to return elements that match this.

So this works as a single:

return get_reader_xml()->xpath("/ReaderDetails/Reader[Status='Available']");

But If I change the value to an array, like below, I get a syntax error message.

return get_reader_xml()->xpath("/ReaderDetails/Reader[Status=('Available', 'Busy')]");

Obviously I know what syntax error is, but everything I've read up on seems to suggest you can give comma separated values here... what mistake am I making?

Upvotes: 0

Views: 110

Answers (2)

ThW
ThW

Reputation: 19482

You need to create a condition from the array. This can be done combining an array_map() with implode().

$xml = <<<'XML'
<ReaderDetails>
  <Reader Status='Available'/>
  <Reader Status='Busy'/>
  <Reader Status='Broken'/>
</ReaderDetails>
XML;

$statusValues = ['Available', 'Busy'];
$condition = implode(
    ' or ',
    array_map(
        function($status) {
            return '@Status="'.$status.'"';
        },
        $statusValues
    )
);
$expression = '/ReaderDetails/Reader['.$condition.']';

var_dump($expression);

$details = new SimpleXMLElement($xml);
foreach ($details->xpath($expression) as $reader) {
    var_dump((string)$reader['Status']);
} 

Output:

string(60) "/ReaderDetails/Reader[@Status="Available" or @Status="Busy"]" 
string(9) "Available" 
string(4) "Busy"

Upvotes: 0

pr1nc3
pr1nc3

Reputation: 8338

return get_reader_xml()->xpath("/ReaderDetails/Reader[Status='Available' or Status='Busy']");



return get_reader_xml()->xpath("/ReaderDetails/Reader[Status='Available'][Status='Busy']");

You could pass multiple parameters like above ways.

Upvotes: 1

Related Questions