Adam
Adam

Reputation: 1309

Fetch specific nodeValue from multi Xpath query

I have this multipel Xpath query

    $data = $xpath->query("//li/span[contains(@class, 'cmil_salong')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_time')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_versions')]/div[contains(@class, 'mv_3d')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_versions')]/div[contains(@class, 'mv_txt')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_rs')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_btn')]/a[contains(@class, 'smallYellowBtn smallBtn')]/@href");

That fetches six (6) nodeValues.

I have tried with $node->nodeValue->item(0) but that gives me Fatal error: Call to a member function item() on string in.

Question: Is it possible to be more specific in the foreach loop, what nodeValue i want to echo? (sorry for pseudo code, just for illustration of my problem):

foreach ($this->xpathquery as $node) { 
    echo 'This is query reuslt of query 0: ' .$node->nodeValue->item(0) .'<br>'>;
    echo 'This is query reuslt of query 1: ' .$node->nodeValue->item(1) .'<br>'>;
    echo 'This is query reuslt of query 2: ' .$node->nodeValue->item(2) .'<br>'>;
    echo 'This is query reuslt of query 3: ' .$node->nodeValue->item(3) .'<br>'>;
    echo 'This is query reuslt of query 4: ' .$node->nodeValue->item(4) .'<br>'>;
    echo 'This is query reuslt of query 5: ' .$node->nodeValue->item(5) .'<br>'>;
 }

(I think I'm running xpath v1 on php 5.6.10)

Upvotes: 1

Views: 91

Answers (1)

The fourth bird
The fourth bird

Reputation: 163577

I think that in your foreach the variable $node are of type DOMElement or DOMAttr and those do not have a method item.

But because you get 6 nodeValues, maybe you can add using the '$key' in your foreach construct:

foreach ($this->xpathquery as $key => $node) {

You can then check for the $key like this:

foreach ($this->xpathquery as $key => $node) {
    if ($key === 0) {
        echo $node->nodeValue;
    }
}

According to your comment, maybe another option might be to check for the nodeType of $node.

This can be 'DOMElement' or 'DOMAttr'.

And then do a check for the class attribute or the nodeName:

foreach ($this->xpathquery as $key => $node) {
    if ($node->nodeType === 1) {
        if ($node->hasAttribute('class')) {
            switch ($node->getAttribute('class')) {
                case "cmil_salong":
                    echo $node->nodeValue;
                    break;
                case "mv_3d":
                    echo $node->nodeValue;
                    break;
                // etc ..
            }
        }
    }
    if ($node->nodeType === 2) {
        if ($node->nodeName === 'href') {
            echo $node->nodeValue;
        }
    }
}

Upvotes: 1

Related Questions