PHP DOM文本替换

时间:2016-10-31 18:26:46

标签: php dom xml-parsing

我需要一些动态做PHP DOM文本替换的帮助。在我的研究中,我发现了一段看起来很有前途的PHP DOM代码片段,但作者没有提供有关它如何工作的方法。代码的链接是:http://be2.php.net/manual/en/class.domtext.php

因此,这就是我在将代码作为DOM的新手接近时所做的。

    $doc = new DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->loadXML($myXmlString);

    $search = 'FirstName lastname';  
    $replace = 'Jack Daniels';      

    $newTxt = domTextReplace( $search, $replace, DOMNode &$doc, $isRegEx = false );
    Print_r($newTxt);

我希望domTextReplace()返回$ newTxt。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这里有一个使用该功能的工作示例:

<?php

$myXmlString = '<root><name>FirstName lastname</name></root>';

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($myXmlString);

$search = 'FirstName lastname';
$replace = 'Jack Daniels';

// The function doesn't return any value
domTextReplace($search, $replace, $doc, $isRegEx = false);

// Now the text is replaced in $doc

$xmlOutput = $doc->saveXML();

// I put xml header to display the results correctly on the browser
header("Content-type: text/xml");
print_r($xmlOutput);

// I copied here the function for everyone to find it quick
function domTextReplace( $search, $replace, DOMNode &$domNode, $isRegEx = false ) {
  if ( $domNode->hasChildNodes() ) {
    $children = array();
    // since looping through a DOM being modified is a bad idea we prepare an array:
    foreach ( $domNode->childNodes as $child ) {
      $children[] = $child;
    }
    foreach ( $children as $child ) {
      if ( $child->nodeType === XML_TEXT_NODE ) {
        $oldText = $child->wholeText;
        if ( $isRegEx ) {
          $newText = preg_replace( $search, $replace, $oldText );
        } else {
          $newText = str_replace( $search, $replace, $oldText );
        }
        $newTextNode = $domNode->ownerDocument->createTextNode( $newText );
        $domNode->replaceChild( $newTextNode, $child );
      } else {
        domTextReplace( $search, $replace, $child, $isRegEx );
      }
    }
  }
}

这是输出:

<root>
  <name>Jack Daniels</name>
</root>