4

I am trying to get all the title elements and save them in an array.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<mylist>
    <element>
        <id>1</id>
        <title>Example 1</title>
        <status>2</status>
        <my_status>2</my_status>
    </element>
    <element>
        <id>2</id>
        <title>Example 2</title>
        <status>1</status>
        <my_status>1</my_status>
    </element>
    <element>
        <id>3</id>
        <title>Example 3</title>
        <status>2</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>4</id>
        <title>Example 4</title>
        <status>3</status>
        <my_status>6</my_status>
    </element>
    <element>
        <id>5</id>
        <title>Example 5</title>
        <status>1</status>
        <my_status>6</my_status>
    </element>
</mylist>

PHP:

$crawler = new Crawler();
$crawler->addXmlContent($data);

$result = $crawler->filterXPath('/mylist/element[not(status=3) and my_status=6]/title/text()');

The elements nodes needs to satisfy some conditions, so calling $result->count() should print 2 (Example 3 & Example 5), but it prints 0.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
allnex
  • 335
  • 3
  • 12

2 Answers2

1

The XPath should be:

$result = $crawler->filterXPath('//mylist/element[not(status=3) and my_status=6]/title/text()');

as per OP @allnex's prior edit to the question.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
0

From filteXpath annotation

 * The XPath expression is evaluated in the context of the crawler, which
 * is considered as a fake parent of the elements inside it.
 * This means that a child selector "div" or "./div" will match only
 * the div elements of the current crawler, not their children.

Then inside method $xpath = $this->relativize($xpath); is applied where your path is modified.

For me most simple solution was just to use relative path like ./mylist.

But if you can understand what's going on here https://github.com/symfony/dom-crawler/blob/master/Crawler.php#L958 absolute path should be possible, I think

Alexander
  • 450
  • 1
  • 4
  • 12