質問

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
役に立ちましたか?

解決

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;

他のヒント

I found a workaround: simply call cloneNode() and return the clone:

return $element->cloneNode();

I agree that this is weird behavior...I don't understand why PHP does this, but at least there's a workaround that still allows you to use document fragments. For more complex fragments you may need to pass true to cloneNode to tell it to make a deep copy, I'm not sure.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top