简体   繁体   English

PHP DOMDocument:获取节点的内部 HTML

[英]PHP DOMDocument: Get inner HTML of node

When loading HTML into an <textarea> , I intend to treat different kinds of links differently.将 HTML 加载到<textarea> ,我打算以不同的方式对待不同类型的链接。 Consider the following links:考虑以下链接:

  1. <a href="http://stackoverflow.com">http://stackoverflow.com</a>
  2. <a href="http://stackoverflow.com">StackOverflow</a>

When the text inside a link matches its href attribute, I want to remove the HTML, otherwise the HTML remains unchanged.当链接内的文本与其href属性匹配时,我想删除 HTML,否则 HTML 保持不变。

Here's my code:这是我的代码:

$body = "Some HTML with a <a href=\"http://stackoverflow.com\">http://stackoverflow.com</a>";

$dom = new DOMDocument;
$dom->loadHTML($body, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

foreach ($dom->getElementsByTagName('a') as $node) {
    $link_text = $node->ownerDocument->saveHTML($node->childNodes[0]);
    $link_href = $node->getAttribute("href");
    $link_node = $dom->createTextNode($link_href);

    $node->parentNode->replaceChild($link_node, $node);
}

$html = $dom->saveHTML();

The problem with the above code is that DOMDocument encapsulates my HTML into a paragraph tag:上面代码的问题是DOMDocument把我的HTML封装成一个段落标签:

<p>Some HTML with a http://stackoverflow.com</p>

How do I get it ot only return the inner HTML of that paragraph?我如何让它只返回该段落的内部 HTML?

You need to have a root node to have a valid DOM document.您需要有一个根节点才能拥有有效的 DOM 文档。

I suggest you to add a root node <div> to avoid to destroy a possibly existing one.我建议您添加一个根节点<div>以避免破坏可能存在的节点。

Finally, load the nodeValue of the rootNode or substr() .最后,加载 rootNode 或substr()nodeValue

$body = "Some HTML with a <a href=\"http://stackoverflow.com\">http://stackoverflow.com</a>";
$body = '<div>'.$body.'</div>';

$dom = new DOMDocument;
$dom->loadHTML($body, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

foreach ($dom->getElementsByTagName('a') as $node) {
    $link_text = $node->ownerDocument->saveHTML($node->childNodes[0]);
    $link_href = $node->getAttribute("href");
    $link_node = $dom->createTextNode($link_href);

    $node->parentNode->replaceChild($link_node, $node);
}

// or probably better :
$html = $dom->saveHTML() ;
$html = substr($html,5,-7); // remove <div>
var_dump($html); // "Some HTML with a http://stackoverflow.com"

This works is the input string is :这是有效的输入字符串是:

<p>Some HTML with a <a href=\"http://stackoverflow.com\">http://stackoverflow.com</a></p>

outputs :输出:

<p>Some HTML with a http://stackoverflow.com</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM