How to filter by id with Symfony 2 Dom Crawler?

12,908

Symfony2 DOM Crawler filter internally uses DOMXPath, so you can find answer for your question on this thread

query for filter should be something like(note that code bellow is untested, I'm sure link above will help you)

//*[@id='elementId']
Share:
12,908
Sukhrob
Author by

Sukhrob

Blogger & Software Engineer with an Entrepreneurial Mindset

Updated on July 19, 2022

Comments

  • Sukhrob
    Sukhrob almost 2 years

    This works

    $this->assertEquals(1, $crawler->filter('.elementClass')->count()); // filter by class
    

    But, this doesn't seem to work.

    $this->assertEquals(1, $crawler->filter('#elementId')->count()); // filter by id
    

    Any ideas?

  • Sukhrob
    Sukhrob over 11 years
    Thank you for your answer. I used both filter() and filterXPath() methods. But, they didn't work.
  • Igor
    Igor over 11 years
    You have tried something like $crawler->filter('//yourtagname[@id="1"]')->count() and it didnt work?
  • Sukhrob
    Sukhrob over 11 years
    By the way, I am filtering HTML, not XML.
  • Sukhrob
    Sukhrob over 11 years
    $crawler->filter('//yourtagname[@id="1"]')->count() shows error "Unexpected symbol". $crawler->filterXPath('//yourtagname[@id="1"]')->count() does not show error. But, it cannot find the element with id.
  • Igor
    Igor over 11 years
    Yup it seams that filter should work only for css selectors (github.com/symfony/DomCrawler/blob/master/Crawler.php) ** * Filters the list of nodes with a CSS selector. * * This method only works if you have installed the CssSelector Symfony Component.
  • Igor
    Igor over 11 years
    I dont think filtering tags in HTML should be different than filtering XML tags. Maybe you can omit one / like "/yourtagname[@id='elementId']" . I can not try code on my machine right now, so i'm guessing
  • Sukhrob
    Sukhrob over 11 years
    I installed CssSelector. Otherwise, my filter with class shouldn't have worked.
  • Igor
    Igor over 11 years
    Yeah I know that, I just copypasted more text then I should :) I just wanted to say that you should use filterXPath for your need. filter method is only for css
  • Sukhrob
    Sukhrob over 11 years
    No, it didn't. It is really strange.
  • Igor
    Igor over 11 years
    You marked this answer as correct, do you solve problem and what is the final solution?
  • Sukhrob
    Sukhrob over 11 years
    You were right. Even $this->assertEquals(1, $crawler->filter('#elementId')->count()); works. In my company, we use short open tags. I forgot to enable that. Thank you very much for your help, icrew. Beware, short open tags are bad :(.