S
S
Shimpanze2020-06-15 07:32:51
PHP
Shimpanze, 2020-06-15 07:32:51

Is it possible to use xpath expressions inside an if condition?

Hello!

Is it possible to use xpath expressions inside an if condition?

Example:

foreach( $elements as $item ) {

  // у итерируемого в данный момент элемента class = foo?
  if ( $xpath->query( "self::node()[contains(@class, 'foo')]", $item ) ) {
        print "yes";
    }
    else {
        print "no";
    }
}


This code doesn't work. Even if you enter a non-existent class, it will still return yes (true).

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shimpanze, 2020-06-15
@Shimpanze

Guessed it myself.
Since xpath returns a collection, you just need to check the number of elements returned. It's pretty easy to do this:

if ( $xpath->query( "self::node()[contains(@class, 'foo')]", $item )->length ) // класс есть!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question