0

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.

1

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks sorry I should have asked this from the begging but is there an easy way to do this for the attributes too. Thank you.
0

Yes you can through the {} sytax here it goes:

$xmlString = '<uploads token="vwl3u75llktsdzi">
  <attachments>
    <attachment myattr="attribute value">123456789</attachment>
  </attachments>
</uploads>';

$xml  = simplexml_load_string($xmlString);
echo "attachment attribute: " . $xml->{"attachments"}->attributes()["myattr"] " \n";
echo " uploads attribute: " . $xml->{"uploads"}->attributes()["token"] . "\n";

you can replace "attachments" with $myVar or something

remember attributes() returns an associative array so you can get the keys with php array_keys() or do a foreach cycle.

Comments

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.