Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php xpath get node where attribute equals

Tags:

php

I have an xml how can I get the node in levelone that has an attribute called myatt whose value is a and then access it's myval. I tried referencing other posts to make it work but it doesn't seem to work what's wrong with my xpath

$this->myXmlObj->xpath("//levelone[myfield[attributes/myatt='a]]]"));

<myxml>
  <levelone>
      <myfield myatt="a" myval="aa" />
      <myfield myatt="b" myval="bb" />

  </levelone>  
  <leveltwo>
      <myfield myatt="c" myval="dd" />
      <myfield myatt="c" myval="dd" />
  </leveltwo>
</myxml>

edit 1

array
  0 => 
    object(SimpleXMLElement)[41]
      public '@attributes' => 
        array
          'myval' => string 'a' (length=40)

edit 2

    $myVar = $this->myXmlObj->xpath("//levelone/myfield[@myatt='a']");
    $myOutput = ((string)$myVar[0]->attributes()->myVal;
like image 341
user391986 Avatar asked Aug 18 '26 22:08

user391986


1 Answers

Attributes in XPATH are referenced with @attr syntax. So, you could retrieve aa with the following xpath

//levelone/myfield[@myatt='a']/@myval

Which means, grab all myfield elements that have attribute myatt equal to 'a'. Then, from those, select the value of their myval attributes. Note that this could be multiple results.

A handy place to test XPATH expressions is at http://chris.photobooks.com/xml/default.htm.

like image 77
skabbes Avatar answered Aug 21 '26 17:08

skabbes



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!