Search code examples
phpgarbage-collectioncreation

Returning element within DocumentFragment fails, because node no longer exists


Here is a testcase that highlights an error I've run into. I think the node is being destroyed/garbage collected/something after the function returns -- is there a better way I can go about this?

function render($doc) {

    $fragment = $doc -> createDocumentFragment();
    $fragment -> appendXML('<iframe foo="bar"/>');
    return $fragment -> childNodes -> item(0);
}

$doc = new \DOMDocument();
$element = render($doc);

// Exception: Couldn't fetch DOMElement. Node no longer exists
echo $element -> tagName; // fails -- because element no longer exists

Solution

  • Since you're creating only one element there is no need to make a fragment. Just create the element and set its attribute.

    function render($doc) {
    
        $element = $doc -> createElement('iframe');
        $element -> setAttribute('foo', 'bar');
        return element;
    }
    
    $doc = new DOMDocument();
    $element = render($doc);
    
    echo $element -> tagName;