Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPATH Get Attribute of Current Node

Tags:

php

xpath

Having trouble getting the attribute of the current node in PHP and making a condition based on that attribute...

Example XML

<div class='parent'>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
</div>

What I am trying to do is traverse the XML in PHP and do different things based on the class of the element/node

Eg.

$doc->loadHTML($xml_string);
$xpath = new DOMXpath($doc);
$nodeLIST = $xpath->query("//div[@class='parent']/div");
foreach ($nodeLIST as $node) {
    if (CURRENT DIV NODE ATTRIBUTE EQUALS TITLE) {
        SET $TITLE VARIABLE TO THE TEXT() OF THE CURRENT NODE
    }
    ELSEIF(CURRENT DIV NODE ATTRIBUTE EQUALS CHILD){
        SET $CHILD VARIABLE TO THE TEXT() OF THE CURRENT NODE
    }
}

I've tried all kind of things like the following...

if ($xpath->query("./[@class='title']/text()",$node)->length > 0) { }

But all i keep getting is PHP errors saying that my XPATH syntax is not valid. Can anyone help me?

like image 770
Nemesisdan Avatar asked Dec 30 '25 16:12

Nemesisdan


2 Answers

You can achieve this by using getAttribute() method. Example:

foreach($nodeLIST as $node) {
    $attribute = $node->getAttribute('class');
    if($attribute == 'title') {
        // do something
    } elseif ($attribute == 'child') {
        // do something
    }
}
like image 159
user1978142 Avatar answered Jan 01 '26 05:01

user1978142


$node->getAttribute('class') gives you the attribute value, $node->textContent the string contents of the node. I wouldn't dive into XPath to read out the string value.

like image 23
Martin Honnen Avatar answered Jan 01 '26 05:01

Martin Honnen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!