3

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;

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

skabbes thanks so much that works for matching the node but i'm not getting the value as a string i'm getting a structure still (see edit 1)
@user391986, SimpleXML will only return elements from XPath queries, regardless of whether you ask for an attribute, string, number, etc. in the query.
I see thanks so should I do like in edit2 or is there a better way to extract the value?
I assume you're using DOMXPath->query, in which case you'll need to pull the attribute out with $xpathResult->nodeValue. You could also use DOMXPath->evaluate instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.