111111
111111

Reputation: 16148

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.

Upvotes: 0

Views: 2426

Answers (2)

GCoro
GCoro

Reputation: 71

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.

Upvotes: 0

user895378
user895378

Reputation:

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

Upvotes: 5

Related Questions