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']
Author by
Sukhrob
Blogger & Software Engineer with an Entrepreneurial Mindset
Updated on July 19, 2022Comments
-
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 over 11 yearsThank you for your answer. I used both filter() and filterXPath() methods. But, they didn't work.
-
Igor over 11 yearsYou have tried something like $crawler->filter('//yourtagname[@id="1"]')->count() and it didnt work?
-
Sukhrob over 11 yearsBy the way, I am filtering HTML, not XML.
-
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 over 11 yearsYup 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 over 11 yearsI 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 over 11 yearsI installed CssSelector. Otherwise, my filter with class shouldn't have worked.
-
Igor over 11 yearsYeah 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 over 11 yearsNo, it didn't. It is really strange.
-
Igor over 11 yearsYou marked this answer as correct, do you solve problem and what is the final solution?
-
Sukhrob over 11 yearsYou 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 :(.