0

I'm trying to have DomCrawler select all DIVs that IDs contain "author-"

I currently have

$list = $crawler->filter('div[id*="actor-"]')->each(function (Crawler $node, $i) { return $node->text(); }); var_dump($list);

But that doesn't return any results, is there any selector like this?

1 Answers1

1

You can use contains() in your XPath like this:

$list = $crawler->filterXPath('div[contains(@id, "actor-")]')->each(function (Crawler $node, $i) {
  return $node->text();
});
var_dump($list);

Edit: From the conversation below, the XPath should be div[contains(@id, "actor-")]/b/a.

xabbuh
  • 5,801
  • 16
  • 18
  • Fatal error: Uncaught exception 'Symfony\Component\CssSelector\Exception\SyntaxErrorException' with message 'Expected operator, but –  Jan 11 '16 at 11:52
  • I changed filter to filterXPath and it's still empty –  Jan 11 '16 at 11:55
  • Sorry, the answer should indeed have used the `filterXPath()` method (I updated it). Can you show a small example HTML string where this does not work? – xabbuh Jan 11 '16 at 11:56
  • `
     1981 Ghost Story
    Ricky Hawthorne
    ` I'm trying to get "Ghost Story"
    –  Jan 11 '16 at 11:58
  • Sorry if this is super simple, this is my first time ever using SymFony –  Jan 11 '16 at 11:58
  • Looks like you then want to replace `author-` in the XPath with `actor-`. By the way, you will also have to filter this a bit more as you are only interested in the content of the a element. – xabbuh Jan 11 '16 at 11:59
  • Well that was a massive derp on my part, how would I filter it more? add ->filter('b > a') after the filterXPath? –  Jan 11 '16 at 12:02
  • You be able to do that with a single XPath expression like `div[contains(@id, "author-")]/b/a` (I didn't test it). But the actual solution depends on how your HTML documents look like (it might be trickier if you have variants of it). – xabbuh Jan 11 '16 at 12:05
  • Please make sure to replace `author-` with `actor-` in the XPath from my last comment. – xabbuh Jan 11 '16 at 12:20
  • I did, I have it `filterXPath('div[contains(@id, "actor-")]/b/a')` but it still returns `array(0) { }` –  Jan 11 '16 at 12:22
  • 1
    That works for me. I guess that's related to some other code you have then. – xabbuh Jan 11 '16 at 12:25
  • If it doesn't work, you might need to add two slashes before the div (or whatever element you're targeting), like so: `filterXPath('//div[contains(@id, "actor-")]')`. – zen Jun 29 '18 at 15:01