PHP DomDocument - 如何将节点中的文本替换为另一个节点

时间:2013-12-13 16:04:15

标签: php xml dom domdocument nodes

我有一个节点:

<p>
    This is a test node with Figure 1.
</p>

我的目标是用子节点替换“图1”:

<xref>Figure 1</xref>

这样最终结果将是:

<p>
    This is a test node with <xref>Figure 1</xref>.
</p>

提前谢谢。

2 个答案:

答案 0 :(得分:2)

Xpath允许您从文档中获取包含字符串的文本节点。然后,您必须将其拆分为文本和元素(外部参照)节点的列表,并在文本节点之前插入该节点。最后删除原始文本节点。

$xml = <<<'XML'
<p>
    This is a test node with Figure 1.
</p>
XML;
$string = 'Figure 1';

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

// find text nodes that contain the string
$nodes = $xpath->evaluate('//text()[contains(., "'.$string.'")]');
foreach ($nodes as $node) {
  // explode the text at the string
  $parts = explode($string, $node->nodeValue);
  // add a new text node with the first part
  $node->parentNode->insertBefore(
    $dom->createTextNode(
      // fetch and remove the first part from the list
      array_shift($parts)
    ),
    $node
  );
  // if here are more then one part
  foreach ($parts as $part) {
    // add a xref before it
    $node->parentNode->insertBefore(
      $xref = $dom->createElement('xref'),
      $node
    );
    // with the string that we used to split the text
    $xref->appendChild($dom->createTextNode($string));
    // add the part from the list as new text node
    $node->parentNode->insertBefore(
      $dom->createTextNode($part), 
      $node
    );
  }
  // remove the old text node
  $node->parentNode->removeChild($node);
} 

echo $dom->saveXml($dom->documentElement);

输出:

<p>
    This is a test node with <xref>Figure 1</xref>.
</p>

答案 1 :(得分:1)

您可以先使用getElementsByTagName()查找您要查找的节点,然后从该节点的nodeValue中删除搜索文本。现在,创建新节点,将nodeValue设置为搜索文本,并将新节点附加到主节点:

<?php

$dom = new DOMDocument;
$dom->loadHTML('<p>This is a test node with Figure 1</p>');

$searchFor = 'Figure 1';

// replace the searchterm in given paragraph node
$p_node = $dom->getElementsByTagName("p")->item(0);
$p_node->nodeValue = str_replace($searchFor, '', $p_node->nodeValue);

// create the new element
$new_node = $dom->createElement("xref");
$new_node->nodeValue = $searchFor;

// append the child element to paragraph node
$p_node->appendChild($new_node);

echo $dom->saveHTML();

输出:

<p>This is a test node with <xref>Figure 1</xref></p>

Demo.