Search code examples
phpsymfonydomdomcrawler

How to use symfony dom parser


I am trying to use Symfony Crawler.

So I have checked this article.

What I want to do is to get the 3,335.00(The second argument)

For now, I try sentence like this, but it is wrong.

$crawler = $crawler->filter('body > div[@class="cell_label"]');

How can I do it??

<body>
<div class="cell__label">  Value1  </div> <div class="cell__value cell__value_"> 2,355.00 </div>
<div class="cell__label">  Value2  </div> <div class="cell__value cell__value_"> 3,355.00 </div>
<div class="cell__label">  Value3  </div> <div class="cell__value cell__value_"> 4,355.00 </div>
</body>

$crawler = new Crawler($url);
$crawler = $crawler->filter('body > div[@class="cell_label"]');//// no work...

foreach ($crawler as $domElement) {
    var_dump($domElement);
}

Solution

  • I can see several issue here:

    1. Using $crawler->filter() implies you must pass a css selector as a parameter, not XPath expressions, so use 'body > div.cell__label' or 'body div[class^="cell__"]' if you need to select all div with a class that starts with cell__, btw you have a typo in cell_label (one underscore).

    2. The Crawler accepts DOMNodeList, DOMNode, array or string as a constructor parameters, not a url to a remote resource (but I assume it may be just an arbitrary variable name you used there). Technically url is a string as well, but not XML formatted string.

    3. If you want to use XPath expression use $crawler->filterXPath(), like that:

      $nodes = $crawler->filterXPath('//div[contains(@class, "cell__label")]');

    Here's a documentation on how to use XPath - https://www.w3.org/TR/xpath/