duancao2082 2015-08-20 08:54
浏览 56

PHP - SimpleXMLElement类型的重载对象与ArrayObject不兼容

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'

  • 写回答

1条回答 默认 最新

  • dorpbn1027 2015-08-20 09:27
    关注

    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
                    )
    
            )
    
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?