Search code examples
phpsimplexml

php simplexmlelement directly access element


I have a simple XML structure like, that when parse with simplexml_load_string generates this:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [token] => rs2rglql9c8ztem
        )

    [attachments] => SimpleXMLElement Object
        (
            [attachment] => 112979696
        )
)

the XML structure:

<uploads token="vwl3u75llktsdzi">
  <attachments>
    <attachment>123456789</attachment>
  </attachments>
</uploads>

I can get to the only actually important value "123456789" through iteration but that is a faf. Is there a way I can access it directly, ideally using the names of the elements.

I need to able to get attributes to ideally.


Solution

  • The simplest way to store the textual node value of a SimpleXMLElement in its own variable is to cast the element to a string:

    $xml = simplexml_load_string($str);
    $var = (string) $xml->attachments->attachment;
    echo $var;
    

    UPDATE

    In accordance with the further question in your comment, the SimpleXMLElement::attributesdocs method will also return a SimpleXMLElement object which can be accessed in the same manner as the above solution. Consider:

    $str = '<uploads token="vwl3u75llktsdzi">
      <attachments>
        <attachment myattr="attribute value">123456789</attachment>
      </attachments>
    </uploads>';
    
    $xml  = simplexml_load_string($str);
    $attr = (string) $xml->attachments->attachment->attributes()->myattr;
    echo $attr; // outputs: attribute value