I would like to be able to use SimpleXMLElement
Object as an Associative array.
I am trying to convert it using the ArrayObject
class.
What is so special in a SimpleXMLElement
Object that it is not compatible with ArrayObject
class?
Note: I am able to convert it in other ways but I am curious why this method does not work.
$dom = new DOMDocument();
$dom->loadHTML($html);
...
var_dump(new ArrayObject(simplexml_import_dom($dom)));
Gives me: Uncaught exception 'InvalidArgumentException' with message 'Overloaded object of type SimpleXMLElement is not compatible with ArrayObject'
I think you are casting it wrong
$dom = new DOMDocument();
$dom->loadHTML("<html><body>Hello</body></html>");
$myArray = (Array)simplexml_import_dom($dom);
echo $myArray["body"]; //prints "hello"
Explanation
ArrayObject suppose to get an object and convert it to a array.
What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE, (specifically a libxml resource).
Edit
cast the entire xml to array:
$dom = new DOMDocument();
$dom->loadHTML("<html><body><div><span>Hello</span></div></body></html>");
$myArray = json_decode(json_encode(simplexml_import_dom($dom)),true);
print_r($myArray);
result:
Array
(
[body] => Array
(
[div] => Array
(
[span] => Hello
)
)
)