Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3961fad

Browse files
committed
feature #7033 [DomCrawler] Document XPath expression evaluation (jakzal)
This PR was merged into the master branch. Discussion ---------- [DomCrawler] Document XPath expression evaluation Documents symfony/symfony#19430 Commits ------- 156b047 [DomCrawler] Document XPath expression evaluation
2 parents b8cda8d + 156b047 commit 3961fad

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

components/dom_crawler.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,58 @@ and :phpclass:`DOMNode` objects:
282282

283283
$html = $crawler->html();
284284

285+
Expression Evaluation
286+
~~~~~~~~~~~~~~~~~~~~~
287+
288+
The ``evaluate()`` method evaluates the given XPath expression.
289+
The return value depends on if the expression operates on simple values
290+
(like HTML attributes), or a subset of the current document.
291+
If the expression evaluates to a scalar value, an array of results will be
292+
returned. If the expression evaluates to a DOM document, a new ``Crawler``
293+
instance will be returned.
294+
295+
This behavior is best illustrated with examples::
296+
297+
use Symfony\Component\DomCrawler\Crawler;
298+
299+
$html = '<html>
300+
<body>
301+
<span id="article-100" class="article">Article 1</span>
302+
<span id="article-101" class="article">Article 2</span>
303+
<span id="article-102" class="article">Article 3</span>
304+
</body>
305+
</html>';
306+
307+
$crawler = new Crawler();
308+
$crawler->addHtmlContent($html);
309+
310+
$crawler->filterXPath('//span[contains(@id, "article-")]')->evaluate('substring-after(@id, "-")');
311+
// array:3 [
312+
// 0 => "100"
313+
// 1 => "101"
314+
// 2 => "102"
315+
// ]
316+
317+
$crawler->evaluate('substring-after(//span[contains(@id, "article-")]/@id, "-")');
318+
// array:1 [
319+
// 0 => "100"
320+
// ]
321+
322+
$crawler->filterXPath('//span[@class="article"]')->evaluate('count(@id)');
323+
// array:3 [
324+
// 0 => 1.0
325+
// 1 => 1.0
326+
// 2 => 1.0
327+
// ]
328+
329+
$crawler->evaluate('count(//span[@class="article"])');
330+
// array:1 [
331+
// 0 => 3.0
332+
// ]
333+
334+
$crawler->evaluate('//span[1]');
335+
// Symfony\Component\DomCrawler\Crawler { }
336+
285337
Links
286338
~~~~~
287339

0 commit comments

Comments
 (0)