如何在 PHP 中将源 html 附加到 DOMElement?

发布于 2024-10-12 17:55:20 字数 174 浏览 6 评论 0原文

有没有办法将源 html 附加到 DOMElement 中?像这样的事情:

$trElement->appendSource("<a href='?select_user=4'>Username</a>");

它会解析该片段然后附加它。

Is there a way of appending source html into a DOMElement? Something like this:

$trElement->appendSource("<a href='?select_user=4'>Username</a>");

It would parse that fragment and then append it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半世蒼涼 2024-10-19 17:55:20

您正在寻找

- DOMDocumentFragment::appendXML — 追加原始 XML 数据

手册示例:

$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML(); 

You are looking for

- DOMDocumentFragment::appendXML — Append raw XML data

Example from Manual:

$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML(); 
通知家属抬走 2024-10-19 17:55:20

如果您在范围内没有对 文档根 的引用,您始终可以通过 ownerDocument属性:

$frag = $trElement->ownerDocument->createDocumentFragment();
$frag->appendXML("<a href='?select_user=4'>Username</a>");
$trElement->appendChild($frag);

If you don't have a reference to the document root in scope, you can always access it via the ownerDocument property of an arbitrary node:

$frag = $trElement->ownerDocument->createDocumentFragment();
$frag->appendXML("<a href='?select_user=4'>Username</a>");
$trElement->appendChild($frag);
小糖芽 2024-10-19 17:55:20

是的,您可以使用 DOMDocument::createDocumentFragment

$fragment = $dom->createDocumentFragment();
$fragment->appendXML('<a href="select_user=4">Username</a>');
$element->appendChild($fragment);

在这种情况下,使用普通的 会更简单createElement 调用:

$el = $dom->createElement('a', 'Username');
$el->setAttribute('href', 'select_user=4');
$element->appendChild($el);

在每种情况下,$element 都是要向其附加代码的 DOM 元素。

Yes, you can do this with DOMDocument::createDocumentFragment:

$fragment = $dom->createDocumentFragment();
$fragment->appendXML('<a href="select_user=4">Username</a>');
$element->appendChild($fragment);

In this case, it would be simpler to do it with a normal createElement call:

$el = $dom->createElement('a', 'Username');
$el->setAttribute('href', 'select_user=4');
$element->appendChild($el);

In each case, $element is the DOM element to which you want to append your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文