0

给定一个部分 HTML 片段,例如

<div id="article">
    <p>Some text</p>
    <p>More text</p>
    <pre><code>
         echo $variable;
    </code></pre>
</div>

我想遍历文本节点并对它们应用一个函数,函数的作用并不重要,但如果它是 pre 代码块中的文本则无关紧要。

鉴于它是部分代码块,我认为我需要使用DOMDocument->createDocumentFragment(). 但是我怎样才能遍历文本节点然后保存输出而不<html>创建额外的标签,就像saveHTML()默认情况下所做的那样?

4

2 回答 2

1

您可以使用文档片段。循环遍历文本节点是容易的部分,找到它们有点棘手。为此,下面的示例使用 XPath 查询来查找不是<pre>元素后代的所有文本节点。

$doc = new DOMDocument;
$xpath = new DOMXPath($doc);

$frag = $doc->createDocumentFragment();
$frag->appendXML(<<<'HTML'
<div id="article">
    <p>Some text</p>
    <p>More text</p>
    <pre><code>
         echo $variable;
    </code></pre>
</div>
HTML
);

$text_nodes = $xpath->query('descendant::text()[not(ancestor::pre)]', $frag);
foreach ($text_nodes as $text_node) {
    $text_node->data = strrev($text_node->data);
}

// Print the div
echo $doc->saveHTML($frag->firstChild);

这将打印出如下内容:

<div id="article">    
<p>txet emoS</p>    
<p>txet eroM</p>    
<pre><code>
         echo $variable;
    </code></pre>
</div>

有用的网址:

于 2013-06-17T20:25:23.433 回答
0

你为什么使用 DomDocument?

为什么不从“远程源”读取 HTML,然后使用 file_put_contents() 将其保存为服务器上的文件

http://php.net/manual/en/function.file-put-contents.php

于 2013-06-17T19:58:20.027 回答