SimpleXMLElement Object
(
[0] => CEM
)
There is a SimpleXMLElement
Object like this. I tried accessing it with $object->0
and $object->{0}
. But it is giving a php error. How do we access it with out changing it to another format.
SimpleXMLElement Object
(
[0] => CEM
)
There is a SimpleXMLElement
Object like this. I tried accessing it with $object->0
and $object->{0}
. But it is giving a php error. How do we access it with out changing it to another format.
From your print_r
output it might not be really obvious:
SimpleXMLElement Object
(
[0] => CEM
)
This is just a single XML element containing the string CEM, for example:
<xml>CEM</xml>
You obtain that value by casting to string (see Basic SimpleXML usageDocs):
(string) $object;
When you have a SimpleXMLElement
object and you're unsure what it represents, it's easier to use echo $object->asXML();
to output the XML and analyze it than using print_r
alone because these elements have a lot of magic that you need to know about to read the print_r
output properly.
An example from above:
<?php
$object = new SimpleXMLElement('<xml>CEM</xml>');
print_r($object);
echo "\n", $object->asXML(), "\n";
echo 'Content: ', $object, "\n"; // echo does cast to string automatically
Output:
SimpleXMLElement Object
(
[0] => CEM
)
<?xml version="1.0"?>
<xml>CEM</xml>
Content: CEM
In your case, it appears as you do print_r($object) and $object it's an array so what you are viewing is not an XML objet but an array enclosed in the display object of print_r()
any way, to access a simpleXML object you can use 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 access data with square braces or through array_keys() or do a foreach cycle.
In your specific case may be just
echo $object[0]; // returns string "CEM"