Skip to content

[DomCrawler] Document XPath expression evaluation #7033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 10, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions components/dom_crawler.rst
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,58 @@ and :phpclass:`DOMNode` objects:

$html = $crawler->html();

Expression Evaluation
~~~~~~~~~~~~~~~~~~~~~

The ``evaluate()`` method evaluates the given XPath expression.
The return value depends on if the expression operates on simple values
(like HTML attributes), or a subset of the current document.
If the expression evaluates to a scalar value, an array of results will be
returned. If the expression evaluates to a DOM document, a new ``Crawler``
instance will be returned.

This behavior is best illustrated with examples::

use Symfony\Component\DomCrawler\Crawler;

$html = '<html>
<body>
<span id="article-100" class="article">Article 1</span>
<span id="article-101" class="article">Article 2</span>
<span id="article-102" class="article">Article 3</span>
</body>
</html>';

$crawler = new Crawler();
$crawler->addHtmlContent($html);

$crawler->filterXPath('//span[contains(@id, "article-")]')->evaluate('substring-after(@id, "-")');
// array:3 [
// 0 => "100"
// 1 => "101"
// 2 => "102"
// ]

$crawler->evaluate('substring-after(//span[contains(@id, "article-")]/@id, "-")');
// array:1 [
// 0 => "100"
// ]

$crawler->filterXPath('//span[@class="article"]')->evaluate('count(@id)');
// array:3 [
// 0 => 1.0
// 1 => 1.0
// 2 => 1.0
// ]

$crawler->evaluate('count(//span[@class="article"])');
// array:1 [
// 0 => 3.0
// ]

$crawler->evaluate('//span[1]');
// Symfony\Component\DomCrawler\Crawler { }

Links
~~~~~

Expand Down