Access an element's parent with PHP's SimpleXML?

前端 未结 3 1572
半阙折子戏
半阙折子戏 2020-12-09 09:30

I\'m iterating through a set of SimpleXML objects, and I can\'t figure out how to access each object\'s parent node. Here\'s what I want:

$divs = simplexml-         


        
3条回答
  •  囚心锁ツ
    2020-12-09 10:24

    $div->get_parent_node(); // Sadly, there's no such function.

    Note that you can extend SimpleXML to make it so. For example:

    class my_xml extends SimpleXMLElement
    {
        public function get_parent_node()
        {
            return current($this->xpath('parent::*'));
        }
    }
    

    And now all you have to do is modify the code you use to create your SimpleXMLElement in the first place:

    $foo = new SimpleXMLElement('');
    // becomes
    $foo = new my_xml('');
    
    $foo = simplexml_load_string('');
    // becomes
    $foo = simplexml_load_string('', 'my_xml');
    
    $foo = simplexml_load_file('foo.xml');
    // becomes
    $foo = simplexml_load_file('foo.xml', 'my_xml');
    

    The best part is that SimpleXML will automatically and transparently return my_xml objects for this document, so you don't have to change anything else, which makes your get_parent_node() method chainable:

    // returns $grandchild's parent's parent
    $grandchild->get_parent_node()->get_parent_node();
    

提交回复
热议问题